加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 20:17:45 所属栏目:百科 来源:网络整理
导读:Evakaka在博客中提出了一种我以前没用过的碰撞检测方法,不过总而言之碰撞检测的核心 就是看两个精灵所在位置有没有重叠。所以无论是用pointsContain还是比较位置都是大同 小异。 在Scene中添加碰撞检测函数: bool isRectCollision (Rect rect1,Rect rect2)

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:多写博客,帮助自己,方便他人!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读