Cocos2d 碰撞检测

Cocos2d 碰撞检测

Cocos Creator 3.3.0

刚学这游戏引擎,碰了些问题,在此记录

开启碰撞检测

玩过 UE4 ,TriggerBox 上手直接用,到这引擎出了挺多问题,官方文档也写得不行
要开启碰撞检测,需要先添加两个 Component

注意:碰撞的两个物体都需要开启这两个 Component,但是事件只需要写一个

首先是RigiBody2D,这是刚体

刚体 Component 开启碰撞检测,刚体类型不能是 Static,貌似这个没有碰撞检测

第二个 Component 是Colliders

添加了 RigiBody2DColliders 之后就有了碰撞检测

注册碰撞事件,事件类型改一改枚举参数即可

// 获取碰撞Component对象
let triggerBox: BoxCollider2D = this.node.addComponent(BoxCollider2D);

// 注册碰撞事件
triggerBox.on(Contact2DType.BEGIN_CONTACT, (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: null) => {
    console.log("触发 Trigger Box");
}, null);

比起这个引擎的编辑器,我更习惯用代码,这是测试代码,仅供参考

onLoad() {
    // 获取 TriggerBox 节点的大小
    let layout: UITransform = this.node.getComponent(UITransform);
    let triggerBoxHeight = layout.contentSize.height;
    let triggerBoxWidth = layout.contentSize.width;

    // RigidBody 绑定 Layout
    let rigidBody: RigidBody2D = this.node.addComponent(RigidBody2D);
    // RigidBody 启用碰撞检测
    rigidBody.enabledContactListener = true;
    // RigidBody 设置为 Kinematic ,静态刚体没有碰撞检测
    rigidBody.type = ERigidBody2DType.Kinematic;

    // TriggerBox 绑定 Layout
    let triggerBox: BoxCollider2D = this.node.addComponent(BoxCollider2D);
    // 配置 TriggerBox
    triggerBox.size = size(triggerBoxWidth, triggerBoxHeight);
    // 配置触发 TriggerBox 回调事件
    triggerBox.on(Contact2DType.BEGIN_CONTACT, (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: null) => {
        console.log("触发 Trigger Box");
        console.log(selfCollider.worldPoints);
        console.log(otherCollider.worldPoints);
        // 防止二次碰撞
        otherCollider.destroy();
        console.log("删除 otherCollider TriggerBox");
    }, null);

}

补充(吐槽)

整个碰撞检测真麻烦,官方文档也很一般,浏览器调试了好几个小时才找到问题
Position是相对坐标,世界坐标不能直接修改,写脚本和设置参数就很难受
😦

Cocos2d 碰撞检测 结束

posted @ 2021-10-08 20:57  .NET好耶  阅读(431)  评论(0编辑  收藏  举报