21
\$\begingroup\$

Suppose I have three layers: a foreground, an intermediate-ground and a background. What is involved in using these three layers to create parallax scrolling?

\$\endgroup\$

5 Answers 5

20
\$\begingroup\$

Divide the position of each layer by the “distance” you want it to have from the camera.

For example: Create a couple of variables to represent the camera position, cameraX and cameraY. Set these to equal the position of your character, possibly adding on a bit extra in the direction of movement.

The main layer would just be positioned at

mainLayer.x = -cameraX;

the middle layer at something like

middleLayer.x = -cameraX * 0.5;

and the far layer at

farLayer.x = -cameraX * 0.2;

Change the constants as needed.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ What Iain said, plus I take the "parallax factor" (1, 0.5 and 0.2 in Iain's code) and make it a parameter describing my layers, that way I can adjust the parallax subtlety (or at runtime). \$\endgroup\$ Jul 14, 2010 at 21:07
7
\$\begingroup\$

Basically you want objects to move faster, the closer they are to the 'camera'. How you implement that is up to you.

I assign each of my layers a depth, and then as I scroll the scene, for each layer I divide that scroll by the depth of the layer, so that layers that are further away move slower.

\$\endgroup\$
5
\$\begingroup\$

A layer that's "further back" would need to scroll at a fraction of the speed of the foreground layer. Half the speed implies double the distance. Other effects like tinting to simulate fog, etc, might also add to the illusion.

\$\endgroup\$
1
\$\begingroup\$

The best way to do this is to simply render sprites as billboarded quads in 3D. The "gameplay" can happen all on one plane, while the background and foreground can be positioned closer or further in 3d space. That way, the parallax effect is handled for you without you having to do any special coding :-)

\$\endgroup\$
1
  • 3
    \$\begingroup\$ If you do that, you have to either scale up your distant quads to compensate for the distance scaling, or set up a projection matrix that doesn't apply any perspective. It may just be easier to translate the quads yourself. \$\endgroup\$
    – munificent
    Jul 14, 2010 at 20:56
0
\$\begingroup\$

Make the bottom layer scroll by subtracting from its position, draw the middle layer as normal, and make the top layer scroll at the speed of the bottom layer divided by two.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .