Столкновение работает только на запад и север - PullRequest
1 голос
/ 19 июня 2019

В основном у меня есть изображение космического корабля, который должен столкнуться с инопланетянином.
Однако инопланетяне обнаруживают столкновения только на западной и северной стороне.
Я хочу, чтобы он сталкивался со всеми сторонами изображения.

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
  }
}

1 Ответ

0 голосов
/ 19 июня 2019

Ваш алгоритм не учитывает размеры изображений с корабля.По крайней мере, не для всех случаев.

Вот пример с измененной процедурой обнаружения:

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>
...