cocos creator 碰撞检测

1.普通的碰撞检测

a.给精灵添加boxCollision

 

b.代码里面开启碰撞管理

cc.director.getCollisionManager().enabled = true;//开启碰撞功能cc.director.getCollisionManager().enabledDebugDraw = true;//开启调试功能,碰撞体上面会有碰撞范围

c.碰撞回调函数

/**
 * 当碰撞产生的时候调用
 * @param  {Collider} other 产生碰撞的另一个碰撞组件
 * @param  {Collider} self  产生碰撞的自身的碰撞组件
 */
onCollisionEnter(other, self){}
onCollisionStay(other, self){}
onCollisionExit(other, self){}

2.物理引擎的碰撞检测

a.添加刚体和刚体碰撞

b.开启物理系统 和碰撞

cc.director.getPhysicsManager().enabled = true;
cc.director.getCollisionManager().enabled = true;

c.设置是否需要回调

this.rigidBody  = this.node.getComponent(cc.RigidBody);
this.rigidBody.enabledContactListener = true;

或者面板设置

d.回调函数


 // 只在两个碰撞体开始接触时被调用一次
    onBeginContact: function (contact, selfCollider, otherCollider) {
    },

    // 只在两个碰撞体结束接触时被调用一次
    onEndContact: function (contact, selfCollider, otherCollider) {
    },

    // 每次将要处理碰撞体接触逻辑时被调用
    onPreSolve: function (contact, selfCollider, otherCollider) {
    },

    // 每次处理完碰撞体接触逻辑时被调用
    onPostSolve: function (contact, selfCollider, otherCollider) {
    }

 

注意:开启碰撞管理功能和物理引擎功能必须放在最前面,即代码的最前面,最好是放在canvas上面

CocosCreator实现的 解救人质 游戏,学会碰撞检测rescue.7z // Bullet.js cc.Class({ extends: cc.Component, properties: { mSpeed: 300, }, // LIFE-CYCLE CALLBACKS: // onLoad () {}, start() { var manager = cc.director.getCollisionManager(); // 获取碰撞检测系统 manager.enabled = true; }, update(dt) { // 设置子弹移动,当超出屏幕范围未发生碰撞时自动销毁 this.node.y += this.mSpeed * dt; if (this.node.y > 580) { console.log('超出屏幕范围,子弹销毁!'); this.node.destroy(); } }, /** * 当碰撞产生的时候调用 * @param {Collider} other 产生碰撞的另一个碰撞组件 * @param {Collider} self 产生碰撞的自身的碰撞组件 */ onCollisionEnter: function (other, self) { console.log('on collision enter'); if (other.tag == 1) { // 子弹碰到人质时,解救失败! console.log('解救人质失败!'); var failLabel = this.node.parent.getChildByName('failLabel'); failLabel.active = true; this.node.destroy(); } else if (other.tag == 2) { // 子弹碰到敌人时,解救成功! console.log('解救人质成功!'); var successLabel = this.node.parent.getChildByName('successLabel'); successLabel.active = true; this.node.destroy(); } }, /** * 当碰撞产生后,碰撞结束前的情况下,每次计算碰撞结果后调用 * @param {Collider} other 产生碰撞的另一个碰撞组件 * @param {Collider} self 产生碰撞的自身的碰撞组件 */ onCollisionStay: function (other, self) { console.log('on collision stay'); }, /** * 当碰撞结束后调用 * @param {Collider} other 产生碰撞的另一个碰撞组件 * @param {Collider} self 产生碰撞的自身的碰撞组件 */ onCollisionExit: function (other, self) { console.log('on collision exit'); } });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值