Creator 3.8 实现类似割绳子的效果

割绳子效果视频:Cocos Creator 3.8实现割绳子的效果_哔哩哔哩_bilibili

简单说一下思路

首先做一个预制体Link,作为绳子的一小段,后面通过代码生成一些Prefab连接成一条绳子,Link需要添加动态刚体组件RigidBody2D、碰撞组件BoxCollider2D和关节组件HingeJoint2D,参考设置如图:

接着看下节点层级如图:


其中,
Rope是静态刚体,固定绳子的节点;
Hook作为绳子的钩子,添加的组件跟Link预制体一样,但是HingeJoint2D组件的Connected Body要设置为Rope;
Weight相当于糖果的重物,添加的组件也跟Link预制体一样,后面通过代码将HingeJoint2D组件的Connected Body要设置为绳子的最后一个Link。

最后来写代码,给Rope节点挂载一个脚本:

@ccclass('Rope')
export class Rope extends Component {

    @property({ type: RigidBody2D })
    private hook = null;

    @property({ type: Prefab })
    private linkPrefab = null;

    @property({ type: Node })
    private weight = null;

    private links = 50;


    start() {
        this.generateRope();
    }

    generateRope() {
        let previousRB = this.hook;
        for (let index = 0; index < this.links; index++) {
            let link = instantiate(this.linkPrefab)
            let joint = link.getComponent(HingeJoint2D);
            joint.connectedBody = previousRB;
            link.parent = this.node;

            previousRB = link.getComponent(RigidBody2D);
        }

        let joint = this.weight.getComponent(HingeJoint2D);
        joint.connectedBody = previousRB;
        joint.anchor = new Vec2(0, 10);
        joint.connectedAnchor = new Vec2(0, -4);
        this.weight.node.active = true;
    }
}

割绳子可以用射线检测两个点之间的线段穿过哪些碰撞体,然后把检测到的碰撞体对应的Node删除就行了。可以参考文档 射线检测
代码参考:

const results = PhysicsSystem2D.instance.raycast(this.touchStartPoint, this.touchEndPoint);
if (results.length > 0) {
    results[0].collider.node.destroy();
}

其中touchStartPointtouchEndPoint可以通过输入事件系统获取。

2赞

能实现这样的缠绕效果嘛