我试图编写一个函数来检查在某个偏移处重叠的街机物理实体。这是我的代码:
function overlapAtOffsetSprite(object1, object2, offsetX, offsetY)
{
if (typeof(object1.body) === "undefined" || typeof(object2.body) === "undefined"){
return false;
}
var bounds1 = new Phaser.Rectangle(object1.position.x + object1.body.offset.x + offsetX,
object1.position.y + object1.body.offset.y + offsetY,
object1.body.width, object1.body.height);
var bounds2 = new Phaser.Rectangle(object2.position.x + object2.body.offset.x, object2.position.y +
object2.body.offset.y, object2.body.width, object2.body.height);
return Phaser.Rectangle.intersects(bounds1, bounds2);
}
function overlapAtOffset(object1, object2, offsetX, offsetY)
{
if (object1.name == "group")
{
object1.forEach(function(child)
{
if (overlapAtOffset(child, object2, offsetX, offsetY))
return true;
});
}
else if (object2.name == "group")
{
object2.forEach(function(child)
{
if (overlapAtOffset(object1, child, offsetX, offsetY))
return true;
});
}
else
{
return overlapAtOffsetSprite(object1, object2, offsetX, offsetY);
}
return false;
}
基本上,函数overlapAtOffsetSprite
检查偏移处的2个精灵之间的重叠,并且函数overlapAtOffset
通过循环遍历每个组来检查精灵和组之间或2组之间的重叠。精灵并在每个精灵上使用overlapAtOffsetSprite
。 overlapAtOffsetSprite
函数在测试时似乎工作正常,但overlapAtOffset
出错了。
提前致谢。
答案 0 :(得分:0)
哦!经过几个小时的盯着它,我发现了问题。我认为return
函数的forEach
语句是overlapAtOffset
。因此,要解决此问题,我使用for
循环而不是使用forEach
数组的group.children
函数。我还编辑了overlapAtOffsetSprite
以计算精灵的锚点。这是所有感兴趣的人的代码:
function overlapAtOffsetSprite(object1, object2, offsetX, offsetY)
{
if (typeof(object1.body) === "undefined" || typeof(object2.body) === "undefined"){
return false;
}
var bounds1 = new Phaser.Rectangle(object1.position.x + object1.body.offset.x -
object1.anchor.x * object1.width/object1.scale.x +
offsetX, object1.position.y + object1.body.offset.y -
object1.anchor.y * object1.height/object1.scale.y +
offsetY, object1.body.width, object1.body.height);
var bounds2 = new Phaser.Rectangle(object2.position.x + object2.body.offset.x -
object2.anchor.x * object2.width/object2.scale.x,
object2.position.y + object2.body.offset.y -
object2.anchor.y * object2.height/object1.scale.y,
object2.body.width, object2.body.height);
return Phaser.Rectangle.intersects(bounds1, bounds2);
}
function overlapAtOffset(object1, object2, offsetX, offsetY)
{
if (object1.name == "group")
{
for (var i = 0; i < object1.children.length; i++)
{
if (overlapAtOffset(object1.children[i], object2, offsetX, offsetY))
return true;
}
}
else if (object2.name == "group")
{
for (var i = 0; i < object2.children.length; i++)
{
if (overlapAtOffset(object1, object2.children[i], offsetX, offsetY))
return true;
}
}
else
{
return overlapAtOffsetSprite(object1, object2, offsetX, offsetY);
}
return false;
}
修改强>
显然,我正在和自己说话,但是,我知道有人可能会发现这对将来很有用。检查对象是否为群组的更好方法是使用:object1.physicsType == Phaser.GROUP
而不是object1.name == "group"
。