Paralax Scrolling

Posted by Walt on Apr 20, 2010 in Thoughts |

I have been struggling with creating a star-field that scrolls realistically as the camera moves across it. The difficulty is to make the stars wrap. When a star tile exits on one side of the screen it needs to be moved quickly back to the other side of the screen.

A quilt of these tiles can make for a realistic and efficient moving space effect.

The difficulty was in finding a way to reliably move a tile to the opposite side of the screen after the tile had completed it’s journey from the top of the screen down to the bottom.

After thinking about the problem, I came up with a cool solution. Turns out that the motion I was looking for was the same motion as a sawtooth wave -

The low point in the wave represents one side of the screen while the high point represents the other side. I can traverse in either direction along the x axis and all tiles will move properly relative to one another.

In my application the screen is 800 x 600 pixels. I wanted a function which would flip tiles every time they had traversed a complete cycle of the screen.

The basic formula for a sawtooth wave is f(x) = x – floor(x).

Floor founds a number down to the nearest whole number. So the only real challenge was to figure out how to make the sawtooth flip every 800 steps.

The eventual equation I found was:

TileY = (cameraY + tileOffset) / (viewportHeight + tileHeight)  – Floor((cameraY + tileOffset) / (viewportHeight + tileHeight))

That quantity got multiplied by (viewportHeight + tile.height) and everything worked.

See:

The Flash plugin is required to view this object.

Reply

Copyright © 2010 From The Desk Of Walt Schlender All rights reserved. Theme by Laptop Geek.