XNA:如何在游戏中改变纹理参考

本文关键字:改变 纹理 参考 游戏 XNA | 更新日期: 2023-09-27 17:54:59

我目前正在制作一款XNA游戏。到目前为止我都做得很好,但我不知道如何在运行游戏时改变精灵的纹理。这方面的一个例子是。当角色静止时,这是一个图像,当他行走时,这是一个不同的图像。我该怎么做呢?

XNA:如何在游戏中改变纹理参考

运行检查并将实例的Texture2D texture设置为预加载库中的其他纹理。

我通常将content文件夹中的所有纹理加载到字典中,并使用如下:

var StringTextureDic = new Dictionary<string, Texture2D>();
// code that loads all textures into the dictionary, file names being keys
// whenever I need to assign some texture, I do this:
if (!playerIsMoving)
    Player.texture = StringTextureDic["player standing"];
if (playerIsMoving)
    Player.texture = StringTextureDic["player moving"];

实际上,在游戏中改变玩家的纹理是个糟糕的主意。在这种情况下,我更喜欢使用纹理表。

Rectangle frame;
int curFrame;
int frameWidth;  
int frameHeight;
int runAnimationLength;
Update()
{
//Handle your "animation code"
if(playerIsMoving)
     curFrame++; //Running
     if(curFrame == runAnimationLength)
          curFrame =0;
else 
curFrame = 0; //Standing still
}
Draw(SpriteBatch spriteBatch)
{
frame = new Rectangle(curFrame*frameWidth,curFrame*frameHeight,frameWidth,frameHeight);
spriteBatch.Draw(
texture,
position,
**frame**, 
color, 
rotation, 
origin, 
SpriteEffects.None,
1);
}