基于matterjs demo,我还创建了一组生活在一个区域内的尸体。就像在演示中一样,该区域由四个静态实体定义,它们一起定义了一个框。
当装有盒子的尸体疯狂移动时,它们似乎以某种方式穿过墙壁逃脱了。有没有办法防止这种转义形式的发生?也许是定义盒子的另一种方法?
最佳答案
所有这些冲突检测算法实际上都是一个问题。
我最终要做的是添加知道盒子边界的代码,并每300毫秒检查一次是否有任何物体在盒子外面。如果是这样,它将使用Matter.Body.translate将它们重新放回盒子中。
请注意,此代码不使用游戏循环,而是使用事件作为其检查机制执行触发器。最好使用whatsjs游戏循环(每隔多个滴答声运行一次检索)来执行此操作,但当时我没有意识到。
这是我最终使用的代码(在我的情况下,该框与 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 */
}