Book Image

Learning Cocos2d-x Game Development

By : Siddharth Shekar
Book Image

Learning Cocos2d-x Game Development

By: Siddharth Shekar

Overview of this book

Table of Contents (19 chapters)
Learning Cocos2d-x Game Development
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Coding collision detection


To detect collision, we add a new function in the GameplayLayer class that will detect collision between two CCSprites and return a value after checking whether the collision occurred or not.

Add the following to the GameplayLayer.h file:

bool checkBoxCollision(CCSprite* box1, CCSprite *box2);

And at the end of GameplayLayer.cpp, add the following:

bool GameplayLayer::checkBoxCollision(CCSprite* box1, CCSprite *box2)
{
    CCRect box1Rect = box1->boundingBox();
      
    
    CCRect box2Rect = box2->boundingBox();
    
    
    if (box1Rect.intersectsRect(box2Rect))
    {
        return true;
    }
    else
    {
        return false;
    }
}

This code gets the two sprites that are given to it, and then for each of the sprites, it builds a collision box depending upon the position, width, and height of the object.

CCRect has an inbuilt function, which we can use if one rectangle is touching the other rectangle. If it interacts, we return true, and if it doesn...