0
\$\begingroup\$

I'm trying to implement Collision detection using Rectangles for my game but can't seem to get it to work.

Bullets are updated when pressing space every frame so they move across the screen. Apparently so I've been told on here, the collisionbox moves with it as well. I'm getting this by using sprite.getBoundingBox() which sets a datafield Rectangle to this value for each instance.

I have two Arraylists, one holding instances of Monsters and one holding instances of Bullets. They all have collisionRectangles associated with them.

I'm calling the checkCollisions() method from my main render loop every frame as long as there's something in the bullets or monsters arraylist.

/*this handles collisions between bullets and enemies*/
public static void checkCollisions(){
    for (int i = 0; i < Main.currentBullets.size(); i++){
        for (int k = 0; k < Main.currentMonsters.size(); k++){
            if (Intersector.overlaps(Main.currentBullets.get(i).collisionBoxBullet,
                  Main.currentMonsters.get(k).collisionBoxMonster)){
                     System.out.println("Boom headshot");
                }
        }
    }

Why does it keep writing Boomheadshot to standard out even when its not colliding with an enemy?

\$\endgroup\$
0
\$\begingroup\$

In the inner for loop, shouldn't you be incrementing k instead of i? You're doing i++ twice, so at some point, your code is trying to access Main.currentBullets.get(10), which is causing your Index 10, size 10 to get thrown.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ sorry woops, updated that but that wasn't the total problem :) re-edited my question! \$\endgroup\$ – magna_nz Nov 25 '14 at 8:16
  • \$\begingroup\$ OK, next question - what happens with the bullets and enemies as soon as they collide? Are you removing them from their respective collections, or how are you handling this aspect in your code? How far are they travelling across your world? Do they stop moving as soon as they collide, or do they keep moving? \$\endgroup\$ – VictorB Nov 25 '14 at 8:20
  • \$\begingroup\$ what happens with the bullets and enemies as soon as they collide? : nothing atm, just want it to write "boom headshot" for testing, i will have the bullet and enemy removed from the list which will remove them from screen. Haven't done that yet though. The bullets are travelling at velocity = 300 * deltatime. So not too quickly across the screen. As i said before, they will be removed from their collection but I'm only using boomheadshot to test to see if the rectangle collision is happening. As soon as I shoot, it doesn't stop saying "boom headshot" even when it hasn't met target yet. \$\endgroup\$ – magna_nz Nov 25 '14 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.