# Calculating trajectory

I'm just starting with game development and some physics related to that. Basically I want to calculate a trajectory given an initial velocity and as well as an elevation / angle. So I wrote this code in Java (I left out some class related code and such):

int v0 = 30; // m/s
int angle = 60;
double dt = 0.5; // s

double vx = v0 * Math.cos(Math.PI / 180 * angle);
double vy = v0 * Math.sin(Math.PI / 180 * angle);

double posx = 1; // m
double posy = 1;  // m
double time = 0; // s

while(posy > 0)
{
posx +=  vx * dt;
posy += vy * dt;
time += dt;

// change speed in y
vy -= 9.82 * dt; // gravity
}


This seems to work fine. However, is there a better way to do this? Also, is it possible to scale so that 5 meter (in calculation) corresponds to 1 m for the posx and posy variables?

The equations of motion for a projectile are:

x(t) = x0 + v0 * t + 0.5g * t^2


where x0 and v0 are your initial position and velocity respectively ([posx, posy] and [vx, vy] in your code), g is the gravitational acceleration (9.82m/s^2 in your code) and t is the time, in seconds.

So, instead of looping, you can find your projectile's position at any time t.

When you map from physical space to pixel space, you need a single value that scales meters to pixels. You want 5 meters to be 1 pixel, so simply divide your physical quantities related to position by 5.

• I have not tested the equation you provided, although in this case I will have to do this by looping. With an initial velocity of 30 m/s and an elevation of 60 degrees (later converted to radians) I will get the result about 80~ meters (posx). Now what I mean by scaling is that I need to be able to draw this on the screen (hence the looping) and I don't want 1 pixel to represent 1 m in the calculation (imagine how much space) but every 5 m in the calculation should correspond to 1 pixel, e.g. 1 m - on the screen -.. is this better explained? Sep 27, 2013 at 14:26
• You can (and should) still use the equation I provided, even if you're rendering and hence need to loop; what you've implemented is a numerical approximation of what I've given you and is not physically correct, though it's fine in most circumstances. I'll edit my answer to include scaling. Sep 27, 2013 at 14:42