我的基本碰撞检测计算不起作用。即使两个物体没有接触,也会继续检测碰撞

My basic collision detection calculation isn't working. Keeps detecting collision even when two objects are not touching

Ship ship;

Asteroid[] asteroid;

Satellite satellite;

void setup() {
  size (1280, 720);
  noCursor();

  ship = new Ship(100, 50);
  asteroid = new Asteroid[3];
  for (int i = 1; i <= asteroid.length; i++) {
    asteroid[i-1] = new Asteroid(random(60, 99));
    satellite = new Satellite(random(100, 900), random(400, 700), 30);
  }
}

void draw() {
  background(0);
  ship.display();
  ship.move(mouseX, mouseY);
  satellite.display();
  for (int i=0; i < asteroid.length; i++) {
    asteroid[i].display();
    asteroid[i].update();
  }
  boolean collision = hitShip(ship, asteroid);
  if (collision == true);
  print("There is a hit");
}


boolean hitShip(Ship ship, Asteroid []asteroid) {

  float asteroid1 = asteroid[0].getXPos() + asteroid[0].getYPos();
  float asteroid2 = asteroid[1].getXPos() + asteroid[1].getYPos();
  float asteroid3 = asteroid[2].getXPos() + asteroid[2].getYPos();
  float shipLocation = ship.getXPos() + ship.getYPos();


  if (asteroid1 == shipLocation) {
    return true;
  }

  if (asteroid2 == shipLocation) {
    return true;
  }

  if (asteroid3 == shipLocation) {
    return true;
  }

  return false;
}

该程序涉及一个对象 'ship' 使用 mouseX 和 mouseY 坐标在屏幕上移动。目标是防止 'ship' 触碰小行星,如果飞船确实触碰了小行星,我希望控制台打印“有撞击”。

当我 运行 程序时,即使飞船没有接触小行星,控制台也会不断地一遍又一遍地打印“有一个命中”。

如果你有一个 asteroid 在位置 30,50 你的代码会说 asteroid = 80
如果 ship 位于 50,30 位置,则显然不在同一位置但仍为 shipLocation = 80

要解决这个问题,您可以使用 Position classequals 方法:

class Position {
  float x;
  float y;

  public Positon(float x, float y) {
    this.x = x;
    this.y = y;
  }

  public boolean equals(Position position) {
    return (this.x == position.x && this.y == position.y);
  }
}

您还可以将每个 asteroids xy 位置与 ships xy 位置进行比较:

for (int i = 0; i < asteroid.length; i++) {
  if (ship.getXPos() == asteroid[i].getXPos() && ship.getYPos() == asteroid[i].getYPos()) {
    return true;
  }
}