由于某种原因,此碰撞检测算法无法正常工作。我希望在碰撞发生时将警报打印到屏幕上,但是这不会发生。我相信它与return语句有关,我在这里遗漏了一些明显的东西吗?
// checkHit is called in the game loop
Player.prototype.checkHit = function() {
for (var i = 0; i < enemies.length; i++) {
var colliding = testCollisionEntity(this, enemies[i]);
if (colliding) {
alert('hello');
}
}
};
testCollisionEntity = function (entity1,entity2){
var rect1 = {
x: entity1.x - entity1.width / 2,
y: entity1.y - entity1.height / 2,
width: entity1.width,
height: entity1.height,
}
var rect2 = {
x: entity2.x - entity2.width / 2,
y: entity2.y - entity2.height / 2,
width: entity2.width,
height: entity2.height,
}
return testCollisionRectRect(rect1,rect2);
}
testCollisionRectRect = function(rect1,rect2) {
return rect1.x <= rect2.x + rect2.width
&& rect2.x <= rect1.x + rect1.width
&& rect1.y <= rect2.y + rect2.height
&& rect2.y <= rect1.y + rect1.height;
}
答案 0 :(得分:0)
应该是
(rect1.x <= rect2.x + rect2.width && rect1.y <= rect2.y + rect2.height) ||
(rect2.x <= rect1.x + rect1.width && rect2.y <= rect1.y + rect1.height)