Cocos2d-x中实现简单碰撞检测的有Rect包围盒工具,用起来十分便捷。先看代码:
//子弹与敌机的碰撞
for (int i=0; i<allBullet.size(); i++) {
Bullet * nowBullet=allBullet.at(i);
for (int j=0; j<allEnemy.size(); j++) {
Enemy * nowEnemy = allEnemy.at(j);
Rect br(nowBullet->px,nowBullet->py-100,nowBullet->sp->getContentSize().width,nowBullet->sp->getContentSize().height);
Rect er(nowEnemy->ex,nowEnemy->ey,nowEnemy->eSprite->getContentSize().width,nowEnemy->eSprite->getContentSize().height);
if (br.intersectsRect(er)) {
allBullet.eraseObject(nowBullet);
nowBullet->removeFromParentAndCleanup(true);
i--;
nowEnemy->hp=nowEnemy->hp-1;
if (nowEnemy->hp<=0) {
if (nowEnemy->type==1) {
Explode * explode = Explode::createExplode(1, nowEnemy->ex, nowEnemy->ey);
this->addChild(explode,10);
}else{
Explode * explode=Explode::createExplode(2,nowEnemy->ex, nowEnemy->ey);
this->addChild(explode,10);
}
if (nowEnemy->toolID>0) {
auto tool=Tool::newTool(nowEnemy->toolID, nowEnemy->ex, nowEnemy->ey);
this->addChild(tool);
allTool.pushBack(tool);
}
allEnemy.eraseObject(nowEnemy);
nowEnemy->removeFromParentAndCleanup(true);
j--;
}
break;
}
}
}
其实只是声明了两个Rect包围盒,其中前两个值是两个点,后面两个是从那两个点开始取多长的坐标。然后我们在用intersectsRect检测两个包围盒有没有碰撞就可以了。是不是很简单?