adding delta time and transformations

Last time we made a MovingShip program which had a spaceship polygon running
around the window when pressing the arrow keys. The movement of the ship was
dependent on the frames i.e 1px per frame update.

But now the movement of the ship will depend on the time so on the different
systems your app shows you the same result. No matter that the game is
running either at 120fps or 60 fps the speed of the objects will be
the same.

Bellow are the basic concepts that are crucial for game programming.

  1. delta time
  2. transformation
  3. vectors
  4. rotation transform
  5. scale transform
  6. skew transform

Delta time(dt)

We want to move the ship with a velocity of v unit per second instead of
1px per frame. To achieve this we need the time difference between the
last and the current frame.

let say the ship is moving by 12px per second to the right and its world
position for the frame f1 is (x, y).

Now, After some time of f1( dt - elapsed time ), the app is going to draw
the next frame f2. Since the ship is moving to the right, therefore the
value of x should be increased by the covered distance in time dt.

We can calculate the new position of the ship as follow-

dt = time at f2 - time at f1

dt = t2 - t1

covered distance = 12 * dt.

let say the app draws the next frame f2 after 15 milliseconds ie dt =
15ms.

So the new position of the ship would be (x', y).
where x' = x + 12 * 15 / 1000

it was so easy!

Let’s implement this to our MovingShip class and make its movement
independent of the frame. We just have to make some changes to the
previous example.

In order to get the current time we can call System.currentTimemillis()
and System.nanoTime() methods which return long data type values.

Previously we had used these methods in the FrameRate class in the article
designing the Framerate class.

Just make changes to the while loop As shown in this pseudo code bellow

// ct : current time
// lt : last time
// dt : delta time
while(running)
dt = ct - lt
updateObject(dt * 1E-9) // dt * 10 raise to -9
renderFrame()
lt = ct

In the last assign the current time to last time lt = ct;

Now we can use delta time dt in updateObject() method.

// velocity v = 60px/sec
// dt is in seconds
updateObject(dt)
if (up)
ship.ty -= dt * v
if (down)
ship.ty += dt * v
if (left)
ship.tx -= dt * v
if (right)
ship.tx += dt * v

I uploaded the complete code to
Github
for MovingShip class.

continue...

Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *