Friday, October 31, 2008

XNA - Simulating Gravity

Now that we have talked a little about vectors and acceleration and such, lets put together a simple 'game' that takes a few of these things together. We will create a Game Object like we have been doing, but we are going to add an Update method to it that will move the updating of our object inside of it rather than outside.


public void Update(GameTime gameTime)
{
if (position.Y < 400)
{
velocity += new Vector2(0f, (float)(9.8 * gameTime.ElapsedGameTime.TotalSeconds));
}
else
{
velocity.Y = velocity.Y * -0.8f;
}
position += velocity;
}


So we pass the current gameTime into the object and check our location. If we are above 400 all we will do is acellerate based on gravity. Now Real gravity is -9.8 meters per second squared. So since we move "down" in XNA terms by adding to Y rather than subtracting, our Gravity velocity will be 9.8. Now 9.8 is relative in pixels So we are basically saying that 1 pixel is one meter. We could of course scale this. If our sprite is a person and is 25 pixels high and "in real life" that person is 2 meters tall, then really we want 12.5 pixels to represent a meter. So in that case we would scale any acellerations by 12.5 to get a more physically accurate simulation. You will also notice that my acceleration vector is not just [0,9.8] but instead I am multiplying by something you have not yet seen. gameTime.ElapsedTime.TotalSeconds. This is a representation in factional seconds of how long it has been since the last update. So since 9.8 is supposed to be per one second, if we multiply that by how long it has actually been (say 0.02 seconds) we will just get enough for the time that has past. That way no matter how fast or slow our program runs, the gravity acceleration should stay constant.

The only other thing that I am doing here is if my object falls below the 400 pixel mark. I make it bounce. I do this by negating it's Y velocity and scaling it back a little. The closer I scale the Y velocity to 0 the less it bouces back. If I scale it higher that 1 it will bounce higher then when it started in the first place.


Here are the project files.

2 comments:

Aybe said...

Great example,

One thing, when i change -0.8 to -0.98, the object suddenly stick to the ground whereas in real life we'd expect it to still bounce.

How can it get fixed ?

Thank you !

Unknown said...

You would wanna apply a forcevector the way you want it to bounce relative to the amount of energy preserved in the bounce.