您的位置:首页 > 移动开发 > Cocos引擎

Cocos2d-X 3.4版-碰撞检测原理《赵云要格斗》

2015-02-04 18:48 375 查看
Evakaka在博客中提出了一种我以前没用过的碰撞检测方法,不过总而言之碰撞检测的核心

就是看两个精灵所在位置有没有重叠。所以无论是用pointsContain还是比较位置都是大同

小异。

在Scene中添加碰撞检测函数:

bool isRectCollision (Rect rect1, Rect rect2);

///碰撞检测
bool HelloWorld::isRectCollision (Rect rect1, Rect rect2)
{
float x1 = rect1.origin.x;//矩形1中心点的横坐标
float y1 = rect1.origin.y;//矩形1中心点的纵坐标
float w1 = rect1.size.width;//矩形1的宽度
float h1 = rect1.size.height;//矩形1的高度
float x2 = rect2.origin.x;
float y2 = rect2.origin.y;
float w2 = rect2.size.width;
float h2 = rect2.size.height;

if (x1+w1*0.5<x2-w2*0.5)
return false;//矩形1在矩形2左方,两者无碰撞
else if (x1-w1*0.5>x2+w2*0.5)
return false;//矩形1在矩形2右方,两者无碰撞
else if (y1+h1*0.5<y2-h2*0.5)
return false;//矩形1在矩形2下方,两者无碰撞
else if (y1-h1*0.5>y2+h2*0.5)
return false;//矩形1在矩形2上方,两者无碰撞

return true;
}
然后再update函数中不多的调用isRectCollision来判断hero和monster的相对位置关系。

f(hero->IsAttack)//英雄正在攻击
{
log("-----00000000000------00000000");
if(!monster1->Isdead && !monster1->IsHurt)//怪物还没死
{
if(abs(hero->getPositionY()-monster1->getPositionY())<30)//怪物和英雄应该在一个差不多的水平高度上,攻击才有效
{
//检测是否碰撞到怪物,这里要注意要减去一些边框值
if (this->isRectCollision(Rect::Rect(hero->getPositionX(), hero->getPositionY(),hero->GetSprite()->getContentSize().width-70, hero->GetSprite()->getContentSize().height-30), Rect::Rect(monster1->getPositionX(), monster1->getPositionY(), monster1->GetSprite()->getContentSize().width-30,monster1->GetSprite()->getContentSize().height-20)))
{
//                    monster1->HurtAnimation("monster_hurt",2,monster1->MonsterDirecton);//受伤
monster1->HurtAnimation("monster_run",6,monster1->MonsterDirecton);//受伤
log("U are bad man, I'm hurted!!!");
}
}
}
}


PS:多写博客,帮助自己,方便他人!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息