Book Image

Cocos2d-x Cookbook

By : Akihiro Matsuura
Book Image

Cocos2d-x Cookbook

By: Akihiro Matsuura

Overview of this book

Table of Contents (18 chapters)
Cocos2d-x Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Detecting collisions


In an action game, a very important technique is to detect collisions between each sprite. However, it is pretty complicated to detect collisions between rect and rect or rect and point. In this recipe, you will learn how to detect collisions easily.

How to do it...

There are two ways to detect collisions. The first method checks whether a point is contained within the rectangle of the sprite.

Rect rect = sprite->getBoundingBox();
if (rect.containsPoint(Vec2())) {
    CCLOG("the point bumped rectangle");
}

The second method checks whether two sprite's rectangles have overlapped.

if (rect.intersectsRect(Rect(0, 0, 100, 100))) {
    CCLOG("two rectangles bumped");}

How it works...

The Rect class has two properties—size and origin. The size property is the sprite's size. The origin property is the sprite's left-bottom coordinate. Firstly, you get the sprite's rect using the getBoundingBox method.

Using the Rect::containsPoint method by specifying the coordinate, it is possible...