1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Make Your Sprite Move

By

When you think of things moving on the screen in your game, you need to think of them moving in time. For example, if the game runs at 10 frames per second on one computer, but 60 frames per second on another (much faster) computer, the action should not be slower on the slower computer. To do this, think of all "speeds" in the game in pixels per second.

We'll add a SPEED constant to the Player class to reflect how fast the player moves. This SPEED constant will be multipled by the direction (either 1 or -1, to make the player move left or right) as well as the delta.

The delta is an important concept. It's the amount of time (in seconds) since the last frame was drawn. If you take a speed in pixels per second and multiply by seconds since the last frame, you'll get the pixels the player should move in this frame. Doing this keeps everything in sync and makes the game run the same speed at all frames per second.

All that's left is to add an update method to the player class and calculate the delta in the main loop.

def update(delta)
@rect.centerx += SPEED * delta * @dir
end

Calculating the delta is very easy. The clock.tick line returns the number of milliseconds since the last frame, so just multiply milliseconds by 0.001 to get seconds.

delta = clock.tick * 0.001
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Game Programming
  6. Time-based Movement

©2014 About.com. All rights reserved.