碰撞分组
cocos creator中新版本中的碰撞分组功能,能够使开发者更方便地管理碰撞检测
这次我使用飞机大战的项目进行详细介绍

点击编辑可以管理碰撞组件的检测

cocos引擎会根据碰撞分组配对,进行相应的检测
如上图,子弹组会与enemy组进行碰撞检测,hero会与enemy组进行碰撞检测
为节点添加碰撞检测组件

可以选择Editing属性对碰撞区域进行编辑
开启碰撞检测
cc.director.getCollisionManager().enabled=true; 这是一个全局属性,开启后就代表碰撞检测组件可以进行检测了
cc.director.getCollisionManager().enabledDebugDraw = true; 绘制碰撞区域
碰撞事件响应函数
开启了碰撞检测后,每一次碰撞组的碰撞就会在节点的组件中查找碰撞响应函数
| 响应函数 | 响应事件 |
|---|---|
| onCollisionEnter:function(other,self) | 碰撞开始事件(第一次接触) |
| onCollisionStay:function(other,self) | 碰撞持续事件(组件相交) |
| onCollisionExit:function(other,self) | 碰撞结束事件(离开的一瞬间) |
| other参数是指与这个组件碰撞的碰撞器组件 | |
| self参数是指自身的碰撞器组件 |
实战测试
1、分组


2、开启碰撞检测
onLoad() {
cc.director.getCollisionManager().enabled=true;
// cc.director.getCollisionManager().enabledDrawBoundingBox = true;
//开启绘制区域
cc.director.getCollisionManager().enabledDebugDraw = true;
cc.log(this.score);
},
3、编写碰撞事件函数
由于我们只需要子弹碰到敌机一下就可以了,因此只使用了onCollisionEnter 响应函数
enemyfly.js
onCollisionEnter:function(other,self){ //碰撞则播放爆炸动画
if (other.node.group != 'bullet'){
cc.log("bullet");
return ;
}
if(other.node.group == 'bullet') //检测碰撞组
{
other.node.removeFromParent();
this.hp -= 1;
if(this.hp == 0 )
{
// enemyReq.add_Score();
this.node.group = 'default'; //防止播放爆炸动画时继续检测导致神奇的事情发生
var en = this.node.getComponent(cc.Animation);
var na = this.node.name;
en.play(na+"_des"); //播放动画
en.on('finished',function(e){
this.node.removeFromParent();
// var score = this.node.getComponent(cc.Label);
},this);
}
}
},
游戏效果

本文介绍CocosCreator新版本中的碰撞分组功能,通过飞机大战项目详细讲解如何设置碰撞组并实现碰撞检测,包括开启碰撞检测、编辑碰撞区域及编写碰撞事件响应函数。
742

被折叠的 条评论
为什么被折叠?



