Reputation: 27
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;
}
The program involves an object 'ship' moving around the screen using the mouseX and mouseY coordinates. The goal is to prevent 'ship' from touching the asteroids, if the ship does touch an asteroid I want the console to print "There is a hit".
When I run the program the console constantly prints "There is a hit" over and over again even when the ship is not touching the asteroids.
Upvotes: 0
Views: 69
Reputation: 319
If you have an asteroid
that is at position 30,50
your code would say asteroid = 80
If the ship
is at position 50,30
it is obviously not at the same position but would still be shipLocation = 80
To solve this you could use a Position class
with an equals
method:
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);
}
}
You can also compare every asteroids
x
and y
position with the ships
x
and y
positions:
for (int i = 0; i < asteroid.length; i++) {
if (ship.getXPos() == asteroid[i].getXPos() && ship.getYPos() == asteroid[i].getYPos()) {
return true;
}
}
Upvotes: 3