Book Image

Cocos2d-x by Example: Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-x by Example: Beginner's Guide

By: Roger Engelbert

Overview of this book

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 repeated 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 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()) - _background...