Animate Sprite Along a Curve path in XNA
I would like to implement a ballistic trajectory in an XNA game and was trying to figure out the best way to make the projectile follow a gravitational curve.
Best thing I can think of is to just calculate the curve first and store in a "Curve" class. Then get开发者_开发问答 the sprite to move along that curve.
But I can't really figure out how to actually move the sprite along that curve.
How would I do this, or is there simply a better way?
Basically you want to use your high school level physics equations of motion (Wikipedia article).
For projectile motion, this is the important equation:
s = s₀ + v₀t + ½at²
(Displacement equals: initial displacement, plus initial velocity multiplied by time, plus half acceleration multiplied by time squared.)
Say you have a projectile moving in 2D. You basically run this equation for each dimension. In the X direction you will have an initial position and some initial velocity but no acceleration.
In the Y direction you will have an initial position, initial velocity, and the acceleration downwards due to gravity.
All you have to do is keep track of the time since your projectile was fired, and draw your sprite at the calculated position.
Here is some rough XNA code - as you can see I can just calculate both axes at once:
Vector2 initialPosition = Vector2.Zero;
Vector2 initialVelocity = new Vector2(10, 10); // Choose values that work for you
Vector2 acceleration = new Vector2(0, -9.8f);
float time = 0;
Vector2 position = Vector2.Zero; // Use this when drawing your sprite
public override void Update(GameTime gameTime)
{
time += (float)gameTime.ElapsedGameTime.TotalSeconds;
position = initialPosition + initialVelocity * time
+ 0.5f * acceleration * time * time;
}
With a little algebra, you can use those same equations of motion to do things like calculating what velocity to launch your projectile at to hit a particular point.
精彩评论