我正在使用 XNA 构建我的第一个游戏,我正在尝试让我的 sprite 运行。 第一个 Sprite 一切正常。 例如:如果我向右走(D),我的 Sprite 向右看,如果我向左走(A),我的 Sprite 向左看,如果我不触摸任何东西,我的 Sprite 就是默认的。 现在我想做的是,如果 Sprite 向右移动,我想交替更改 Sprite (左腿、右腿、左腿等)。xCurrent 是当前绘制的 Sprite xRunRight 是第一个运行的 Sprite,xRunRight1 是在正确运行时必须与 xRunRight 交换的那个。 这就是我现在拥有的:
protected override void Update(GameTime gameTime)
{
float timer = 0f;
float interval = 50f;
bool frame1 = false ;
bool frame2 = false;
bool running = false;
KeyboardState FaKeyboard = Keyboard.GetState();
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if ((FaKeyboard.IsKeyUp(Keys.A)) || (FaKeyboard.IsKeyUp(Keys.D)))
{
xCurrent = xDefault;
}
if (FaKeyboard.IsKeyDown(Keys.D))
{
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
if (frame1)
{
xCurrent = xRunRight;
frame1 = false;
}
else
{
xCurrent = xRunRight1;
frame1 = true;
}
}
xPosition += xDeplacement;
}
任何想法...?我已经坚持了一段时间.. 提前致谢,如果您需要代码中的任何其他部分,请告诉我。
请您参考如下方法:
您忘记重置计时器,您可以在达到timer interval 条件时执行此操作。另外,50 毫秒对于一个间隔来说似乎有点太小了,也许你可以像 400 毫秒那样?
除此之外,看起来不错,它会做你想做的事。
或者,您可以考虑制作用于行走的动画 Sprite 。你要做的是制作一张带有行走动画 Sprite 的图像,一个挨着一个,大小相同。您只绘制此图像的一部分(一个 Sprite )并根据时间在它们之间移动。
下面是一个动画纹理的快速代码:
class AnimatedTexture2D : Texture2D
{
int _numberOfImages;
int _currentImage = 0;
int _timeInterval;
int _spriteWidth;
public Rectangle DrawFromRectangle
{
get
{
return new Rectangle(_currentImage * _spriteWidth, 0, _spriteWidth, this.Height);
}
}
public AnimatedTexture2D(Texture2D entireImage, int spriteWidth, int numberOfImages, int timeInterval)
: base(entireImage.GraphicsDevice, entireImage.Width, entireImage.Height)
{
_numberOfImages = numberOfImages;
_timeInterval = timeInterval;
_spriteWidth = spriteWidth;
Color[] data = new Color[entireImage.Width * entireImage.Height];
entireImage.GetData<Color>(0, new Rectangle(0, 0, entireImage.Width, entireImage.Height), data, 0, entireImage.Width * entireImage.Height);
this.SetData<Color>(data);
}
public void Animate(GameTime gameTime)
{
int totalImageTime = _timeInterval * _numberOfImages;
int currentPoint = (int)gameTime.TotalGameTime.TotalMilliseconds % totalImageTime;
_currentImage = currentPoint / _timeInterval;
}
}
用法相当简单:
1) 在某处声明:
AnimatedTexture2D animatedTexture;
2) 用你的纹理启动它(我有一个 2560x64 的序列,由 40 张 64*64 图像组成),其中各个图像水平并排放置:
animatedTexture = new AnimatedTexture2D(Content.Load<Texture2D>(@"Textures\Loading"), 64, 40, 20);
3) 在您的 Update() 方法中,调用:
animatedTexture.Animate(gameTime);
4) 在您的 Draw() 方法中,调用:
SpriteBatch.Draw(animatedTexture, new Rectangle(20, 20, 64, 64), animatedTexture.DrawFromRectangle, Color.White);
不要忘记第 4 部分中的 DrawFromRectangle! (注意目标矩形使用声明的单个部分宽度,而不是我测试中的整个纹理宽度 2560 像素)
现在,在您的代码中您可以忘记间隔部分和游戏时间部分,您可以只使用它而不是默认部分!
此外,如果您不喜欢我的计时代码(它非常简单但缺少重置动画的方法),请更改它以便您拥有耗时变量,然后像在您自己的代码中一样添加它,并且用它来改变 _currentImage。您甚至可以公开该变量,以便使用它来重置动画(或将其设置为指定点)。
当然,您也可以将默认纹理设为只有一帧的动画纹理,这样您就可以在任何地方使用相同的代码。希望这对您有所帮助!
