I noticed in several game programming related forums, most users specify speed in “pixels per frame” in their 2d games. They just add a magic number to the object position every frame and the object moves.
The problem with this approach (beside movement chaos at different frame rates): it is hard to understand as well as almost impossible to find reasonable speed values without trial and error, since this unit system does not work well with our brains. In the following text, I present an approach to solve the ambiguous unit system problem, that works good for me.
Let us take the 2d game again, where the player character moves 1.5 pixels per frame on the x-axis. To understand how fast this is, we need to translate “per frame” to something meaningful, something we use every day in our real life.
Vehicles specify speed in “distance per hour”, we are used to it. When someone tells me his car makes it up to 200mph I go wow, 0.05555 miles per frame (at 60 fps) does not tell me anything.
I find pixels per second (px/s) being a good unit system for 2D games. A gaming device typically runs at 60 frames per second (fps). When we use px/s, 1.5px per frame become 1.5px * 60fps = player moves 90 px/s.
When we could specify speed as “pixels per second” in your 2D game, it makes it easier to find reasonable values and helps, in my opinion, the code to become more meaningful as well as making it possible to be understood by non-programmers, which is very much needed when (character) properties are specified outside the code-editor, by a level designer for example.
Fortunalety, it is very simple to do that! We just need to specify speed in pixels per second and multiply it by the timestep, before we add it to the object position. Timestep describes how many seconds a frame lasts in this case. At 60 frames per second, one frame lasts 1/60 = 0.016667 seconds.
Here comes a pseudo snippet that moves an object 90px/s, when executed at 60fps:
1 2 3 4 5 6 7 8 | speed = 90; // 90 pixels per second. timestep= 1/60; // duration of one game frame in seconds. // computes how many pixels to move in this (time)step distance = speed * timestep; // moves object by distance object_x = object_x + distance; |
You can, of course, use whatever units you want. Pixels per second is just my personal preference when I move objects around in 2d-space. It is just important that you use meaningful units, if your team is fine with miles per frame, go for it.
Further reading and advanced information on the timestep topic, please head over to: Fix Your Timestep!

Add A Comment