Reputation: 35
I have a view that is 600 pixels in height with 12 boxes, each 50 pixels by 50 pixels. I created a ball where the user clicks that falls based on gravity. I am doing this for a physics demonstration and I am trying to have it as accurate as possible. Currently, the scale that I am working with uses four boxes (or 200 pixels) as one meter. The method that calculates the "y" position gets called 50 times per second (50 fps). When I try to run the program with this code in it, it is off by a decent amount of time.
This is the method that I am calling to update the position:
public double calcY()
{
velocity += acceleration*200/2500;
return(getY()-velocity);
}
I'm multiplying by 200 to convert meters to pixels. And dividing by 2500 because it's getting called 50 times per second so (50)^2 is 2500.
Right now it's not off by a lot. Thanks for the help.
Upvotes: 0
Views: 307
Reputation: 1623
You should start with kinematic equation of motion.
x = x0 + v0*t + 1/2*a*t^2
Acceleration times time squared has the units of position. Here the t, is the absolute time. If you want to compute the position time by frame.
v = v0 + a*dt
x = x0 + v0*dt + 1/2*a*dt^2
Here at each time you compute the final position and velocity and use that as the initial position and velocity of next frame.
Upvotes: 0
Reputation: 20069
Your calculations should never be tied to a fixed frame rate, measure the real time that has expired. FPS can and will vary greatly by factors outside your control.
You can keep track of time expired between calls to calcY() using System.currentTimeMillis() - that might be off a few ms between two calls, but it will be pretty precise across multiple calls.
Also last time I checked fall acceleration wasn't one meter per second, but 9.81 m/s. So your calculated acceleration seems to be off by a factor of 9.81.
Edit: Looking at your formula again, it makes no sense to me.
Upvotes: 2