Search code examples
iphonecocos2d-iphonespritephysicsgame-physics

Game Physics - Not very life-like


In a simple game (cocos2d) I have a made a small physics engine to move a sprite so that it can jump and stand on platforms ect.

To update the position (vertical movement) I use basic kinematics equations in each update:

  • position = oldPosition + velocity(delta) +1/2(gravity)(delta)^2
  • velocity = oldVelocity + (gravity)(delta)

For some reason the game doesn't seem very life-like. It seems to take a long time near the top of an arc, despite how great I make gravity. If I want my sprite to jump the same height, but decelerate and accelerate more quickly, but still jump just as high as before, how should I do that? I hope that makes sense.


Solution

  • Problem here is you have made a mistake with your physics! But that is okay, because it is an easy fix.

    When calling your update method on your sprite's position, you should first set the acceleration. I assume gravity is a constant for this game, and so you only need to set it once. (-9.81, or something similar.)

    You then want to update the velocity of the character in the y direction by velocity = old_velocity + acceleration * time.

    After doing this you then update the position in a similar way: position = old_position + velocity * time.

    The equation you are using to update the position is valid only if delta is the total elapsed time, and not a time-step! (I have assumed delta is a time step, because that's how physics games are usually programmed.)

    I hope this helps! If you want to know more, check out suvat equations, you will see that you can compute a final position if you know an initial velocity and a constant acceleration, where as your game will have a velocity that varies when you do jumping and collisions, and so it does not surprise that it isn't realistic! Any more questions, just comment and I will try to help you further.

    EDIT: I reprogrammed exactly what you have done here with some boxes drawn using OpenGL. Your method of updating the position does not seem to work. The boxes only seem to fall correctly if the dt or timestep is 1.0d, and I am not sure why. Then when they collide with something, they stop all together instead of bouncing. I am not sure exactly why.

    However, I also have another box on the screen which uses the physics I described: v = u + a*t and s = s_last + v*t The box falls exactly as expected and bounces correctly. Due to a simplification, energy is lost in the bouncing.