问题描述
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 class
与 equals
方法结合使用:
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
x
和 y
位置与 ships
x
和 y
位置进行比较:
for (int i = 0; i < asteroid.length; i++) {
if (ship.getXPos() == asteroid[i].getXPos() && ship.getYPos() == asteroid[i].getYPos()) {
return true;
}
}