cocos creator-碰撞检测

碰撞检测文档

刚体自行选择,刚体正常设置分组、tag,tag用于区分是哪个物体被碰撞了

正常在一个node下挂载脚本就行

复制代码
注意:Builtin 2D 物理模块只会发送 BEGIN_CONTACT 和 END_CONTACT 回调消息。

@ccclass('TestContactCallBack')
export class TestContactCallBack extends Component {
    start () {
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
            collider.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
            collider.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
        }

        // 注册全局碰撞回调函数
        if (PhysicsSystem2D.instance) {
            PhysicsSystem2D.instance.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            PhysicsSystem2D.instance.on(Contact2DType.END_CONTACT, this.onEndContact, this);
            PhysicsSystem2D.instance.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
            PhysicsSystem2D.instance.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
        }
    }
    onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        console.log('onBeginContact');
    }

1、需要注意的是 刚体不能两个都是static,否则不会触发碰撞回调

2、碰撞回调的时候不能直接进行node销毁,否则会奔溃

复制代码
    onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        console.log('onBeginContact222'+otherCollider.name);
        console.log('onBeginContact222name:'+selfCollider.name);
        // console.log('onBeginContact222tag:'+selfCollider.tag);

        if(selfCollider.tag==10 && otherCollider.tag==20){
            setTimeout(()=> {
                if(this.node && this.node.isValid) {
                  selfCollider.node.destroy();
                  otherCollider.node.destroy();
                }
              }, 500);
        }
相关推荐
花归去20 分钟前
echarts 柱状图曲线图
开发语言·前端·javascript
老前端的功夫24 分钟前
TypeScript 类型魔术:模板字面量类型的深层解密与工程实践
前端·javascript·ubuntu·架构·typescript·前端框架
Nan_Shu_6141 小时前
学习: Threejs (2)
前端·javascript·学习
G_G#1 小时前
纯前端js插件实现同一浏览器控制只允许打开一个标签,处理session变更问题
前端·javascript·浏览器标签页通信·只允许一个标签页
@大迁世界1 小时前
TypeScript 的本质并非类型,而是信任
开发语言·前端·javascript·typescript·ecmascript
Amumu121381 小时前
React面向组件编程
开发语言·前端·javascript
冰暮流星2 小时前
javascript逻辑运算符
开发语言·javascript·ecmascript
拖拉斯旋风3 小时前
从零开始:使用 Ollama 在本地部署开源大模型并集成到 React 应用
前端·javascript·ollama
德育处主任3 小时前
『NAS』在群晖部署图片压缩工具-Squoosh
前端·javascript·docker
Van_captain5 小时前
rn_for_openharmony常用组件_Breadcrumb面包屑
javascript·开源·harmonyos