creator小功能----浅谈碰撞检测和道具物品拾取 | 附源码collider.zip

碰撞是游戏中经常需要用到的功能。那么怎么去实现碰撞检测呢?

在creator中,有碰撞检测系统 和 物理碰撞系统,是两个独立的模块;

这里我们讨论的是碰撞检测,而不是物理碰撞。

第一步、分组:

给游戏世界中的物体来进行分组,指定节点的分组与分组的碰撞矩阵

第二步、获取分组

代码中获取节点的分组和分组索引: group与groupIndex

node.group


node.groupIndex

第三步、添加碰撞检测区域

为每个节点添加碰撞检测区域-->碰撞器(物体形状), 编辑碰撞区域

   

第四步、开启碰撞检测系统

代码开启碰撞检测系统(默认是关闭碰撞检测),开启和关闭碰撞检测的调试

 properties: {
       
        is_debug: true,
        is_enable: true,
    },   

 onLoad () {
        if(this.is_enable){
            var manager = cc.director.getCollisionManager();
            manager.enabled = true;//开启碰撞

            if(this.is_debug){
                manager.enabledDebugDraw = true;//调试模式
            }
        }
    },

第五步、碰撞检测函数

碰撞检测函数响应,发生碰撞检测的节点,会调用这个节点上所有组件的统一的三个接口:

     onCollisionEnter: function (other, self) // 开始

     onCollisionStay: function (other, self)  // 持续

     onCollisionExit: function (other, self)    // 结束

     其中other是与这个节点碰撞的节点的碰撞器组件

     其中self是自身节点的碰撞器组件

     是碰撞器组件,不是节点-->碰撞器组件.node

    /*
    *  A与B碰撞,
    *  对于A上挂载的脚本,A是self,B是other
    *  对于B上挂载的脚本,B是self,A是other
    * 对于这里,次脚本挂在player上的,other就是prop碰撞器组件;self是自己节点的碰撞器组件
    */
    //碰撞开始
    onCollisionEnter: function(other, self){
        console.log("-----get_prop onCollisionEnter----");
        //获取名字
        console.log("enter: other name--", other.node.name, ",self name--", self.node.name);
        //获取节点的分组和分组索引
        console.log("enter: other group--", other.node.group, ",self groupIndex--", self.node.groupIndex);

        //
        if(other.node.groupIndex === 2){
            var _prop = other.node.getComponent("prop");
            console.log("get prop~~~", _prop.prop_type);
        }
    },

    //碰撞持续
    onCollisionStay: function(other, self){
        console.log("-----get_prop onCollisionStay----");
    },

    //碰撞结束
    onCollisionExit: function(other, self){
        console.log("-----get_prop onCollisionExit----");
    },

拾取道具见源码;

源码下载地址

发布了265 篇原创文章 · 获赞 20 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ccnu027cs/article/details/104660976