tags:

views:

76

answers:

1

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?

+3  A: 

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.

Andrew Russell
Awesome. Works pretty well. But any idea how to add an initial angle to this? For example, if the projectile is fired at 0.5 radians?
Adam Haile
@Adam: That is simple trigonometry: `initialVelocity = (cos(0.5), sin(0.5)) * 100`
Andrew Russell
Thanks, I had finally figured it out. Problem I was having was that I didn't realize that the XNA trig methods were looking for radians and not degrees... so I was incorrectly converting them all to degrees first.
Adam Haile