1.两个精灵在同一个父类上,代码如下
CCRect r1 = spr1->boundingBox();
CCRect r2 = spr2->boundingBox();
// 判断是否有交叉
if (r1.intersectsRect(r2)) {
CCLOG("---%s---", "相碰撞了");
}
2.两个精灵不在同一个父类上,代码如下
void collisionDetection(Node* node_1, Node* node_2){
//先转换为世界坐标
Point worldPoint1 = node_1->convertToWorldSpace(node_1->getAnchorPointInPoints());
Point worldPoint2 = node_2->convertToWorldSpace(node_2->getAnchorPointInPoints());
//获取他们的大小
Size contentSize1 = node_1->getContentSize();
Size contentSize2 = node_2->getContentSize();
//获得他们的锚点,因为要把坐标转换为左下角的坐标
Point anchorPoint1 = node_1->getAnchorPoint();
Point anchorPoint2 = node_2->getAnchorPoint();
//构造他们的Rect
Rect r1 = Rect(worldPoint1.x - contentSize1.width * anchorPoint1.x, worldPoint1.y - contentSize1.height * anchorPoint1.y, contentSize1.width, contentSize1.height);
Rect r2 = Rect(worldPoint2.x - contentSize2.width * anchorPoint2.x, worldPoint2.y - contentSize2.height * anchorPoint2.y, contentSize2.width, contentSize2.height);
if (r1.intersectsRect(r2))
{
CCLOG("---%s---", "相碰撞了");
}
}