for (int i = 0; i < asteroidCount; i++) {
asteroids[i].move();
if (asteroids[i].getY() <= 0 || asteroids[i].getY() + asteroids[i].getAsteroidHeight() >= getHeight()) {
asteroids[i].setYDir(-asteroids[i].getYDir());
}
if (asteroids[i].getX() <= 0 || asteroids[i].getX() + asteroids[i].getAsteroidWidth() >= getWidth()) {
asteroids[i].setXDir(-asteroids[i].getXDir());
}
//Collision code for when the asteroid hits the ship
if (ship.getX() < asteroids[i].getX() + asteroids[i].getAsteroidWidth() && ship.getX() + ship.getshipWidth() > asteroids[i].getX() && ship.getY() < asteroids[i].getY() + asteroids[i].getAsteroidHeight() &&ship.getY() + ship.getshipHeight() > asteroids[i].getY()) {
//Game over, stop the timer
t.stop();
JOptionPane.showMessageDialog(this, "Game Over! Asteroid hit the ship.");
System.exit(0);
}
}
repaint();
import javax.swing.*;
import java.awt.*;
public class Asteroids {
//Declare fields
private int xPos, yPos, asteroidHeight, asteroidWidth;
private ImageIcon imgAsteroid;
private int xDir, yDir;
private Color c;
private boolean useImage;
//Create a 3rd constructor that creates a ball using an image
public Asteroids(int x, int y, ImageIcon img) {
xPos = x;
yPos = y;
imgAsteroid = img;
asteroidWidth = img.getIconWidth();
asteroidHeight = img.getIconHeight();
useImage = true;
xDir = 2;
yDir = 2;
}
//Accessor methods to return the values of the fields
public int getX() {
return xPos;
}
public int getY() {
return yPos;
}
public int getAsteroidWidth() {
return asteroidWidth;
}
public int getAsteroidHeight() {
return asteroidHeight;
}
public Image getImage() {
return imgAsteroid.getImage();
}
//Mutator methods to change the values of fields
public void setAsteroidWidth(int width) {
asteroidWidth = width;
}
public void setAsteroidHeight(int height) {
asteroidHeight = height;
}
public void setColor(Color col) {
c = col;
}
public void setImageIcon(ImageIcon imgAsteroids) {
imgAsteroid = imgAsteroids;
}
public void setX(int x) {
xPos = x;
}
public void setY(int y) {
yPos = y;
}
public void draw(Graphics2D g2) {
if (useImage == false) {
g2.setColor(c);
g2.fillOval(xPos, yPos, asteroidWidth, asteroidHeight);
} else {
g2.drawImage(getImage(), xPos, yPos, null);
}
}
//Overload the move method so the parameters determine how many pixels to move
public void move() {
xPos += xDir;
yPos += yDir;
}
public int getXDir() {
return xDir;
}
public void setXDir(int xDir) {
this.xDir = xDir;
}
public int getYDir() {
return yDir;
}
public void setYDir(int yDir) {
this.yDir = yDir;
}
}
My PNG image is interfering with my collision code and I don't know how to fix it. When I collide with the asteroid, it is a decent amount away from the asteroid and the game. I just edited the question to give more information so that it is more easily solvable. It might be a problem with the collision code, but I'm almost certain it's a problem with the PNG image.