# How can I add a parallax effect into my side-scrolling game? [duplicate]

How can I add a parallax effect into my side-scrolling game? I read a lot about parallax scrolling so I know what the logic is and what parallax is but I can't create a dynamic parallax effect.

I have draw and update functions like this:

void UpdateBackground(Background &back)
{
back.x += back.velX * back.dirX;
if(back.x + back.width <= 0)
back.x = 0;
}
void DrawBackground(Background &back)
{
draw_bitmap(back.image, back.x, back.y, 0);

if(back.x + back.width < WIDTH)
draw_bitmap(back.image, back.x + back.width, back.y, 0);
}


So this draws a parallax effect with two background objects but it draws it statically. I'm creating a 2D side-scrolling game and I'm translating my character and my camera position along x axis. So I have to translate my parallax effect with my camera but when I add to background position.x it doesn't work. How can I solve this?

Parallax backgrounds are divorced from reality, you don't need velocities and directions. What you do need is to base the background's X on the camera's position and modified with multiplier to offset the background more slowly so it looks like it is very far away. Different layers of background can look closer by making this magic number bigger, so instead of 0.1f for far away use 0.3f for up close, etc...

An example might look like:

void UpdateBackground(Background &back, float cameraX)
{
back.x = cameraX * 0.1f; // magic number to make the background move slowly
back.x = fmod( back.x, back.width );
}

• It seems this gonna work but it draws only one time.Any change in draw part of my code?Also i'm using java so can i use % instead of fmod ? Commented May 15, 2012 at 21:30
• Yes, you can use float % float in Java for modulus. I think what might be happening is that you need to draw the backgrounds directly as big bitmaps offset by the X, without the camera; since your camera is moving it's moving away from the backgrounds which are staying relative to 0. Commented May 15, 2012 at 23:21
• So how can i achieve this?I have tried and searched a lot but i can't do it. Commented May 16, 2012 at 7:42
• Cool option: If you move the background not slower, but at some speed in the opposite direction as the camera, you can create rotation rather than panning. Commented May 16, 2012 at 14:45
• @DampeS8N How can i do this?Can you answer with code? Commented May 16, 2012 at 20:15