碰撞仅在西侧和北侧起作用

Collision only working west and north sides

基本上我有一张需要与外星人相撞的宇宙飞船的图像。
然而,外星人只检测到西侧和北侧的碰撞。
我希望它在图像的各个方面发生碰撞。

if (ay >= spy && ay <= spy + spaceshipImage.height // North side  
  ||
  spy >= ay && spy <= ay + alienImage.height // South side
) {
  if (spx + alienImage.width >= ax && spx + alienImage.height <= ax + alienImage.height // West side _+
    ||
    spx >= ax && spx <= ax + alienImage.width // East side _+
  ) {
    slives = slives - 1;
    ax = Math.floor(Math.random() * (canvasWidth2 - alienImage.width));
    ay = -100
  }
}

您的算法没有考虑 shaceship 图像的尺寸。至少不是所有情况。

这是一个修改后的检测例程的示例:

spaceshipImage = {};
spaceshipImage.height = 10;
spaceshipImage.width = 10;
alienImage = {};
alienImage.width = 20;
alienImage.height = 20;
ay = 50;
ax = 50;
spx = 70;
spy = 60;

var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d");
context.fillStyle = "#ff0000"
context.fillRect(spx, spy, spaceshipImage.width, spaceshipImage.height)
context.fillStyle = "#00ff00"
context.fillRect(ax, ay, alienImage.width, alienImage.height)
if (spx + spaceshipImage.width >= ax && spx <= ax + alienImage.width && spy + spaceshipImage.height >= ay && spy <= ay + alienImage.height) {
  console.log("hit");
}
<canvas id="canvas"></canvas>