0

I'm having a problem with my Collision method below. the problem is when there are two enemies in the game. It intersects one enemy within the loop, and proceeds to return true for colliding. But if there is a second enemy within this array List It will not be colliding with that second object, therefore causing it to return false and the player continues walking. any idea's on how I can make him stop when he is in contact with ANY enemy, instead of just continuing because he isn't in contact with all the enemies? Thanks, here is the code.

public void checkCollision(){
    ArrayList<Enemy> enemy = c.getEnemyList();
    for ( int i = 0; i < enemy.size(); i++){
        Enemy e = enemy.get(i);

        if (!getBounds().intersects(e.getBounds())){
            walk();
            return;
        }
        if (getBounds().intersects(e.getBounds())){
            if (e.getHP() <= 0){
                c.removeEnemy(e);
                walk();
                return;
            }
            fight();
            if (count == 25 || count == 65){
                int dd = DCalc.calcDmg(atk, atkMAX);
                e.dmg(dd);
            }

    }
    }

}
3
  • suggestion: move this to the Game development site
    – 0x6C38
    Apr 24, 2013 at 0:48
  • wasn't aware of the site, Thank you Mr D for informing me.
    – Evan Nudd
    Apr 24, 2013 at 0:51
  • wish I could move the question myself but not enough reputation. if you flag the question a moderator will do it for you.
    – 0x6C38
    Apr 24, 2013 at 0:53

1 Answer 1

0

This is just another example of the 'early return' problem. This problem manifests when you need to do a check of the format (if ANY, x, else y) or (if ALL, x, else y) and you rephrase it in the format (if FIRST, x, else y).

To solve this, you need to remake the algorithm as follows:

bool collided = false
For each enemy:
    Are we colliding with this enemy?
    If we are, do collision detection and set `collided` to true
end for

If `collided` is false, NOW we can run the code that should only run if we collided with nothing
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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