防止 matterjs 主体逃离预定义区域

Prevent matterjs bodies form escaping a predefined area

基于matterjs demo我还创建了一组生活在一个区域内的身体。就像在演示中一样,该区域由四个静态物体定义,它们共同定义了一个盒子。

当带着盒子疯狂移动身体时,他们似乎以某种方式穿过墙壁逃脱了。有没有办法防止这种转义形式的发生?也许另一种定义盒子的方法?

这实际上是所有这些碰撞检测算法的问题。

我最后做的是添加了解盒子边界的代码,并每 300 毫秒检查一次是否有物体在边界之外。如果是这样,它会使用 Matter.Body.translate 将它们再次放回盒子中。

请注意,此代码不使用游戏循环,而是使用事件来触发其检查机制执行。使用 matterjs 游戏循环(运行 每隔这么多滴答检索一次)会更好,但当时我没有意识到这一点。

这是我最终使用的代码(在我的例子中,盒子和 canvas 本身一样大):

/* `allBodies` is a variable that contains all the bodies that can
 * escape. Use something like `Composite.allBodies(world)` to get 
 * them all but beware to not include the box's borders which are
 * also bodies.
 * `startCoordinates` is an object that contains the x and y
 * coordinate of the place on the canvas where we should move escaped
 * bodies to.
 */
function initEscapedBodiesRetrieval(allBodies, startCoordinates) {

    function hasBodyEscaped(body) {
        var x = body.position.x;
        var y = body.position.y;

        return x < 0 || x > _canvasWidth || y < 0 || y > _canvasHeight;
    }

    setInterval(function() {
        var i, body;

        for (i = 0; i < allBodies.length; i++) {
            body = allBodies[i];
            if (hasBodyEscaped(body)) {
                Matter.Body.translate(body, { x: (startCoordinates.x - body.position.x), y: (startCoordinates.y - body.position.y) });
            }
        }
    }, 300); /* We do this every 300 msecs */ 
}