H3XXX
H3XXX

Reputation: 647

.intersects() from for loop is not working

I have two arraylists here, that contain rockets and projectiles:

public static ArrayList<Projectile> projectiles = new ArrayList<Projectile>();
private static ArrayList<Rocket> rockets = new ArrayList<Rocket>();

Every now and then, a projectile and a rocket are added to the appropriate arraylist:

rockets.add(new NormalRocket(x, -10, 70, 0, 2); // the constructor is (int x, int y, int speed, int dir, int health) but only x and y are relevant.

Both Rocket and Projectile classes have the method:

public Rectangle bounds() {
    return new Rectangle(x, y, width, height);
}

And subclasses such as NormalRocket and MachineGunProjectile also have it:

public Rectangle bounds() {
    return super.bounds();
}

Now, I have a method that checks for collision between the rockets and projectiles like so:

private void collision(){
    for(int i = 0; i < rockets.size(); i++){
        for(int j = 0; j < projectiles.size(); j++){
            if(rockets.get(i).bounds().intersects(projectiles.get(j).bounds())){
                System.out.println("HIT!");
            }
        }
    }
}

But when they do intersect, nothing appears to happen. Does someone know what is going on or does this require more code to debug?

Upvotes: 0

Views: 190

Answers (1)

Andre Ahmed
Andre Ahmed

Reputation: 1891

I will give you some hints to debug your problem

  1. Try to drawtext the x,y positions of your rockets and projectiles.

  2. Try to draw the bounding rectangle too, so that you can see if the bounding rectangles are really drawn correctly or not.

  3. Check the intersection functions by drawing two rectangles that CAN intersect and check the output value.

Upvotes: 1

Related Questions