How to Take Advantage of Parallax in Programming and Video Games

Encora | September 23, 2021

Parallax is a visual effect that has influenced the way video game developers play with our perception.

Here’s how to take advantage of it.


What is Parallax?

Parallax is the effect in which far away objects in a scene seem to move more slowly than closer ones.

When travelling on the road, you might have noticed hills at a distance that seem to stay right in place forever, while smaller road signs seem to be zooming past as you move forward.

What Does This Have to Do with Programming?

If you happen to develop visual media, parallax helps to generate a three-dimensional effect on your TV screen. In a traditional animations, you can create this effect manually. However, in video games, the environment must react to the user. At first, such effect might appear as if it had been generated by magic and it certainly makes it look much more professional.

What Can I Use It in?


Mainly, in 2D gaming—sidescrollers, to be more specific. In a 3D game, you simply position objects where they are supposed to be and the camera takes care of the effect. However, in a 2D environment, you're moving flat items over flat backgrounds.

There is no real depth, so it needs to be simulated to make your environment more fluid.

In addition to games, many modern websites use this technique to generate a sense of depth and movement when scrolling or moving the mouse.

Your creativity is the limit.

How Do You Create It?

It's really simple. For me it was a “duh!” moment when I learned how to do it.

To move a character (or object) horizontally, you must change its position x, like this,

character.x = character.x + 2;

To move the background, you’d need to do the same thing but in the opposite direction,

background.x = background.x - 2;

The various planes that you see in 2D video games are simply many "backgrounds" moving at different speeds. I recommend that you have a speed variable with which to do the calculation so that it will not appear uneven.

var speed = 5;
if (rightKey.IsPressed) {
character.x = character.x + speed;
firstPlane.x = firstPlane.x - speed/2;
secondPlane.x = secondPlane.x - speed/4;

(This is pseudo-code, for illustration purposes)

You can even place objects towards the viewer that appear to be moving at a much faster speed,

foreground.x = foreground.x + speed * 2

There's No Magic (But It Feels Like It)

The magic lies in the fact that you can have as many levels as you wish if you want to create a very dynamic 3D scene.
Depending on what you're doing, you’re not limited to a horizontal plane. It can also be vertical or even in both directions.

It’s a matter of applying it to what you need and to play with the numbers.


Insight Content

Share this Post

Featured Insights

Fill Out Later