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 – initializing our Terrain class


We'll go over these steps next:

  1. The first important method to implement is initTerrain:

    void Terrain::initTerrain () {
        
        _increaseGapInterval = 5000;
        _increaseGapTimer = 0;
        _gapSize = 2;
        
        //init object pools
        for (int i = 0; i < 20; i++) {
              auto block = Block::create();
              this->addChild(block);
              _blockPool.pushBack(block);
        }
    
       _minTerrainWidth = _screenSize.width * 1.5f;
       
        random_shuffle(_blockPattern.begin(), _blockPattern.end());
        random_shuffle(_blockWidths.begin(), _blockWidths.end());
        random_shuffle(_blockHeights.begin(), _blockHeights.end());
       
       this->addBlocks(0);
    }

    We have a timer to increase the width of gaps (we begin with gaps two tiles long).

    We create a pool for blocks so we don't instantiate any during the game. And 20 blocks is more than enough for what we need.

    The blocks we are currently using in the terrain will be stored inside a _blocks vector...