Monday, July 22, 2019

java - 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?


Thanks in advance!



Answer




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.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...