# 2D game physics, doing it right

I have a ball that you can make jump,

I have a sneaking suspicion I'm doing this wrong. It works now, to the extend that gravity pulls the object down toward the ground, but I'm having trouble manipulating the speed of the object.

What this is, is a ball jumping and falling towards the ground.

I have another function called "jump" that just adds a value to it's yVel

I can increase gravity, and it falls faster.

I can increase the jSpeed speed, and it'll rise up longer, but not faster

But I can't get it to do everything faster. It just looks painfully slow, which may or may not be because of my emulator running at 11 fps, on average.

Is it just my emulator, or is it something on my end?

float time = elapsedTime/1000F;
if (speed < maxSpeed){
speed = speed + accel;
}
if(mY + mVelY < Panel.mHeight){ //0,0 is top-left
mVelY += (speed);
}

if (!(mY + height >= Panel.mHeight)){
mVelY = mVelY  + gravity ;}

mX  =  (float) (mX +(mVelX * time));
mY =  (float) (mY + (mVelY * time));

• Why two equal if statements? !>= is the same as <? – deceleratedcaviar Jun 15 '11 at 8:23
• I can't really remember why I did that. I think it had a purpose once... – user8017 Jun 15 '11 at 9:00
• If your goal is to 'do it right', I wouldn't treat gravity as a special case and instead as just a constant acceleration. – The Communist Duck Jun 15 '11 at 10:00

There are some errors:

speed = speed + accel;


acceleration must be multiplied by time to get the change of velocity/speed during this frame:

speed = speed + accel * time;


The same problem is how you handle gravity, you cant simply add it to velocity.

Then you add speed to velocity each frame. Speed is actually the length of the velocity vector. Adding speed to velocity doesn't make sense physically.

You can find a proper implementation of Euler Integration in my answer here, there is a simple example showing how to deal with Acceleration, Velocity and Position.

• That you can't add gravity can be somewhat accurate but is misleading and wrong in most cases because most game engines do recalculate the velocity vector by adding gravity at each time-step, much differently than speed with is added only when acceleration occurs (e.g. user presses left, right, jump, whatever). In that way the velocity for any given time-step is calculated as the sum of all accelerations along time, i.e. it's integral. – Trinidad Jun 16 '11 at 14:57