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 – adding collision detection


Let's see how that translates to code:

  1. Still in Terrain.cpp:

    void Terrain::checkCollision (Player * player) {
    
       if (player->getState() == kPlayerDying) return;
       bool inAir = true;
       for (auto block : _blocks) {
          if (block->getType() == kBlockGap) continue;
          
          //if within x, check y (bottom collision)
          if (player->right() >= this->getPositionX() + block->left() && player->left() <= this->getPositionX() + block->right()) {
                
            if (player->bottom() >= block->top() && player->next_bottom() <= block->top() && player->top() > block->top()) {
               player->setNextPosition(Vec2(player->getNextPosition().x, block->top() + player->getHeight()));
               player->setVector ( Vec2(player->getVector().x, 0) );
               player->setRotation(0.0);
               inAir = false;
               break;
             }       
     ...