首页 > Computer > XNA > XNA Series – Animation Part 2
2009
02-17

XNA Series – Animation Part 2

In our last installment we created a sprite based animation and today I want to extend that a little. We are going to add a velocity to our character and scale his animation based on it. This is actually very simple. First we create 2 floats

public float velocity = 0;
public float maxVelocity = 1;

Then in our Update method, when we detect our key press, rather than updating the position, we will update the velocity + 0.1 for right and -0.1 for left. Then after the keyboard stuff we will update the position by adding the current velocity to the location.

            KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Left))
{
a.velocity -= 0.1f;
a.frameNumber += 0.4f;

}
if (ks.IsKeyDown(Keys.Right))
{
a.velocity += 0.1f;
a.frameNumber += 0.4f;
}
a.position.X += a.velocity;
if (a.velocity > 0) a.direction = 1;
else if (a.velocity < direction =" 0;

Then we also check to see if our velocity is plus or minus to choose our direction. Now that we have a velocity, we can use that to scale our framerate. So rather than just adding 0.4 to our framecount whenever our key was down we will always add 0.4 scaled by our velocity each update

 a.frameNumber += 0.4f * (float)Math.Abs(a.velocity / a.maxVelocity);

as you can see we scale it by velocity/maxVelocity so when velocity is 0, nothing is added. We also take the Absolute value of the scale so that we are always adding to our value (otherwise our animation would run backwards, which may be desired at times). So now as we press our buttons we will see our character speed up and the animation speed up in relation to it.

Here is the source code: SpriteAnimation2.zip

最后编辑:
作者:wy182000
这个作者貌似有点懒,什么都没有留下。

留下一个回复