Game Development Reference
In-Depth Information
Time for action - creating a parallax effect
The parallax effect in our game takes place inside the main loop:
1. So in our
update
method, you will find the following lines of code:
if (_player->getVector().x > 0) {
_background->setPositionX(_background->getPosition().x
- _player->getVector().x * 0.25f);
First, we move the
_background
sprite, which contains the cityscape texture re-
peated three times along the
x
axis, and we move it at one-fourth of the speed of
the
_player
sprite.
2. The
_background
sprite scrolls to the left, and as soon as the first cityscape tex-
ture is off the screen, we shift the entire
_background
container to the right at
precisely the spot where the second cityscape texture would appear if allowed to
continue. We get this value by subtracting where the sprite would be from the total
width of the sprite:
float diffx;
if (_background->getPositionX() < -_background
->getContentSize().width) {
diffx = fabs(_background->getPositionX()) -
_background ->getContentSize().width;
_background->setPositionX(-diffx);
}
So, in effect, we only ever scroll the first texture sprite inside the container.
3. A similar process is repeated with the
_foreground
sprite and the three lamp-
post sprites it contains. Only the
_foreground
sprite moves at four times the
speed of the
_player
sprite. These are coded as follows:
_foreground->setPositionX(_foreground->getPosition().x
- _player->getVector().x * 4);
if (_foreground->getPositionX() < -_foreground
->getContentSize().width * 4) {