MatterJS删除对象函数

MatterJS remove object function

本文关键字:函数 对象 删除 MatterJS      更新时间:2023-09-26

我正在一个小项目上与matter.js一起工作,试图用js函数从matterjs世界中添加和删除对象。

add函数似乎可以工作,remove方法只在添加函数中起作用-

var boxes = [];
function addCircle(Cid, Ccolor, Cradius) {
    boxes[Cid] =  Bodies.circle((w/2), (h/2), Cradius, {
            density: 0.0005,
            frictionAir: 0.06,
            restitution: 0.3,
            friction: 0.01,
            render: { fillStyle: Ccolor, strokeStyle: 'rgba(0,0,0,0)',
            lineWidth: 0,
         }
        });
    boxes[Cid].angle = Math.random() * 0.5;
    boxes[Cid].force.y -= 0.0001;
    World.add(engine.world, boxes[Cid]);
    //World.remove(engine.world, boxes[Cid]);  <-- This one works
}

function removeCircle(Cid) {
    //console.log(boxes[Cid]);
    World.remove(engine.world, boxes[Cid]); // <-- This one doesn't
}

控制台显示删除函数的错误"Cannot read property 'type' of undefined"。有人能告诉我怎么解决这个问题吗?如有任何帮助和建议,我将不胜感激。

要从一个世界中移除一个主体,你需要使用Composite.remove(...)

在你的例子中是:

Composite.remove(engine.world, boxes[Cid]);