Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating gravity in XNA

Tags:

xna

Alright, so I'm trying to create my own Physics engine for a 3D XNA game, and I'm having troubles calculating how much I should move my object by for gravity.

XNA's game timer occurs every 16 milliseconds, so after some calculations, and using 9.81m/s as my gravitational velocity, you can see that you should increase the velocity of the object that has gravity by:

0.15696 meters/16milliseconds
- basically every update call should increase the object by 0.15696 meters

The questions is, how do I convert 0.15696 meters into pixels. Obviously if I just use a 1:1 relationship the object will only move 9.81 pixels/second. Which does not really simulate gravity :P Does anyone have a good idea on how I can determine how many pixels I should move the object by?

Thanks for all the help!

like image 324
cush Avatar asked May 13 '26 03:05

cush


1 Answers

Although 2d game dev is more pixel-centric, 3d game dev doesn't concern itself with pixels for this kind of stuff, but rather units. Unit size is completely arbitrary.

Typically, you have a velocity vector whose magnitude is equivalent to the meters(or feet or ??) per second that your object is going. That way the position is updated each frame by adding this velocity * the elapsed time since last frame (the 16.6666 ms). The acceleration from gravity is added to the velocity vector in the same way:

Vector3 gravity = Vector3.Down * 9.81f;


//in the update loop
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;//0.01666667 (or 16.67 ms) @ 60FPS
velocity += gravity * elapsed; 
position += velocity * elapsed;

In this example, I've arbitrarily established that 1 xna unit == 1 meter.

like image 176
Steve H Avatar answered May 19 '26 05:05

Steve H