Sunday, September 6, 2015

java - Why is my velocity decaying?


Programming in Java. Tinkering around with physics. My entities all have position and velocity. In the main loop, all I'm doing is applying gravity and bouncing off the edges, like so:


    //  add gravity vector
o.velocity.add(GRAVITY.cpy().mul(dt));


// bounce off walls
if ((o.position.x<0 && o.velocity.x<0) || (o.position.x>WORLD_SIZE_X && o.velocity.x>0))
o.velocity.x*=-1;

// bounce off of ground
if (o.position.y<=0.0f) {
o.position.y=0.0f;
if (o.velocity.y<0)
o.velocity.y *= -1;

}

The x and y values of my vectors are just floats.


For the first second it looks like it's working fine, but the vertical velocities slowly decay. Any idea why?



Answer



As long as you only apply constant acceleration (i.e. from constant gravity) Eulers Method is accurate and the ball must bounce forever, reaching its initial position again after each bounce phase. If not, then there is something wrong with the implementation of Euler's Method. Here is how it should look like:


void update(float dt)
{
position += velocity * dt + acceleration * 0.5 * dt * dt;
velocity += acceleration * dt;

// handling only the simple ground collision case here
if(position.x < radius)
{
velocity = -velocity;
}
}

Note the acceleration is constant here, its simply the gravity.


EDIT:


It seems both, the article on gaffergames and the code in the question use a simpler form of Euler's Method, namely:



     position += velocity * dt;
velocity += acceleration * dt;

whereas this one as also shown in this paper:


     position += velocity * dt + acceleration * 0.5 * dt * dt;
velocity += acceleration * dt;

is still capable of correctly integratiing constant accelerations.


Note: This answer is not supposed to mean that the Euler Method is a good choice for complex physics and non-constant accelerations, nor that you should stick to it once you want to add more physics dynamics to your scene. However, if the application will only use constant acceleration, then this method perfectly fits your needs.


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...