前言:creator有碰撞检测系统 +物理碰撞系统,这个是两个独立的模块;
知识点:
代码开启碰撞检测系统(默认是关闭碰撞检测),开启和关闭碰撞检测的调试:
var manager = cc.director.getCollisionManager(); // 获取碰撞检测管理器manager.enabledDebugDraw = true; // 允许绘制碰撞的区域
碰撞检测函数响应,发生碰撞检测的节点,会调用这个节点上所有组件的统一的三个接口:是碰撞器组件,不是节点-->碰撞器组件.node
1.首先给Canvas 画布绑定 enable_collider 脚本
代码如下
cc.Class({
extends: cc.Component,
properties: {
is_enbale: true,
is_debug: true,
},
// use this for initialization
onLoad: function () {
},
start:function(){
if(this.is_enbale==true){
var manager = cc.director.getCollisionManager(); // 获取碰撞管理器
manager.enabled = true; // 开启碰撞
manager.enabledDebugDraw = true; // 允许绘制碰撞的区域
}
},
// called every frame
update: function (dt) {
},
});
给道具绑定的脚本如下
cc.Class({
extends: cc.Component,
properties: {
prop_type: 1,
},
// onLoad () {},
start () {
},
onCollisionEnter: function (other, self) {
console.log("other.name = ", other.node.name, other.node.group, other.node.groupIndex);
if (other.node.groupIndex === 1) { // 表示是PLAYER类型撞到了,道具拾取成功
this.node.removeFromParent();//消失
}
},
// 碰撞持续
onCollisionStay: function (other, self) {
},
// end
// 碰撞结束
onCollisionExit: function (other, self) {
},
// update (dt) {},
});
给player绑定的脚本如下
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 () {
},
// other是道具的碰撞器组件
// self 是自己节点的碰撞器组件
// 碰撞器是一个组件,所以我们可以通过组件 -->节点
// 碰撞开始
onCollisionEnter: function (other, self) {
console.log("other.name = ", other.node.name, other.node.group, other.node.groupIndex);
if (other.node.groupIndex === 2) { // 与道具相撞
var prop = other.node.getComponent("prop");
console.log("我们捡到了道具:", prop.prop_type);
}
},
// 碰撞持续
onCollisionStay: function (other, self) {
},
// end
// 碰撞结束
onCollisionExit: function (other, self) {
},
// called every frame, uncomment this function to activate update callback
// update: function (dt) {
// },
});
再添加计时器和得分就完美了