Time for action – creating a parallax effect
The parallax effect in our game takes place inside the main loop:
- 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 repeated three times along thex
axis, and we move it at one-fourth of the speed of the_player
sprite. - The
_background
sprite scrolls to the left, and as soon as the first cityscape texture 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()) ...