微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

解决方法

如果您有一个位于 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;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。