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.
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");}
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...