Bruce
Bruce

Reputation: 235

Calculating the position of a parallax background (2d)

I'm trying to align 4 different parallax backgrounds in my game. These aren't endless tiling backgrounds like in a space shooter, they don't fill the whole screen. They're a row of trees running along the ground.

My images are bottom left aligned and I'm trying to align them all to the lowest point on the terrain.

I have the following information: The lowest point on the map that I want everything to line up at (is 300). The parallax / scroll factor of the background. The height of the background.

http://i.imgur.com/BRlNP.jpg

I've tried:

background.y = lowestPoint; // doesn't work
background.y = lowestPoint * parallaxFactor; // doesn't work, way off
background.y = lowestPoint + lowestPoint * parallaxFactor; // doesn't work

I'm obviously missing something here.

Basically, I'm trying to calculate where to put the background tile's registration point based on it's parallax factor and lowest point in the terrain.

Ideas?

Upvotes: 0

Views: 2705

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89221

If I understand this correctly; Screen position is calculated as

screenX = (positionX - cameraX) * parallaxFactor
screenY = (positionY - cameraY) * parallaxFactor

Then to align two positions with different parallax factors at some camera position, you need to match screen coordinates:

obj1.screenY = (obj1.positionY - cameraY) * obj1.parallaxFactor
obj2.screenY = (obj2.positionY - cameraY) * obj2.parallaxFactor

(obj1.positionY - cameraY) * obj1.parallaxFactor =
    (obj2.positionY - cameraY) * obj2.parallaxFactor

obj1.positionY =
    (obj2.positionY - cameraY) * F + cameraY

where F = obj2.parallaxFactor / obj1.parallaxFactor.

Similarly for the horizontal direction.

Upvotes: 1

Related Questions