cocos creator基础-(二十)物理引擎碰撞检测

本文详细介绍了游戏开发中物体类型与碰撞矩阵的概念,如何配置碰撞矩阵来决定不同物体类型的碰撞行为,以及如何通过编写碰撞响应函数来监听并处理碰撞事件。同时,文章还解释了如何使用Sensor作为触发器,仅进行碰撞检测而不改变物体运动状态。

1: 理解物体类型和分类,配置碰撞矩阵;
2: 编写碰撞响应函数,监听碰撞事件;
3: 学会了解Sensor来做触发器,只触发碰撞不改变运动;

物体类型与碰撞矩阵

1: 添加物体类型: Add Layer, 每个类型对应一个名字group与groupIndex
2: 创建物体的时候要选择一个类型;
3: 配置碰撞矩阵,决定哪些物体类型碰撞;

 

碰撞事件监听

1: 刚体组件开启碰撞监听;
2: 当有碰撞发生的时候,遍历刚体所在的节点所挂的所有的组件,看组件是否实现了碰撞检测函数,如果是,那么调用;
3: 在需要检测碰撞的组件代码里面编写碰撞响应函数:
  onBeginContact ( contact, selfCollider, otherCollider): 碰撞开始
  onEndContact (contact, selfCollider, otherCollider): 碰撞结束
  onPreSolve(contact, selfCollider, otherCollider); 碰撞持续,接触时被调用;
  onPostSolve (contact, selfCollider, otherCollider); 碰撞接触更新完后调用,可以获得冲量信息

4: 如果把碰撞器设置成了sensor,那么只会做碰撞检测,而不会改变物体碰撞后的运动状态;
  sensor: 用于触发器: 道具, 关卡的出口,入口等;

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {

    },

    // contact 是碰撞对象,本次碰撞的信息
    // selfCollider: 是自己的碰撞器组件
    // otherCollider: 碰撞到的碰撞器组件;
    // 我们可以有碰撞器组件,来获取我们的碰撞的节点对象
    // 碰撞开始
    onBeginContact: function ( contact, selfCollider, otherCollider) {
        console.log("onBeginContact:", otherCollider.node.name, " ", selfCollider.node.name);
        console.log("onBeginContact", selfCollider.node.group, otherCollider.node.group);
        console.log("onBeginContact", selfCollider.node.groupIndex, otherCollider.node.groupIndex);
    },

    // 碰撞结束
    onEndContact: function(contact, selfCollider, otherCollider) {
        console.log("onEndContact");
    },

    // 碰撞持续
    onPreSolve: function(contact, selfCollider, otherCollider) {
        console.log("onPreSolve function");
    },

    // 计算完本次碰撞持续后,调用这个
    onPostSolve: function (contact, selfCollider, otherCollider) {
        console.log("onPostSolve");
    }
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});

 

转载于:https://www.cnblogs.com/orxx/p/10528530.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值