user1449547
user1449547

Reputation: 5

android If else statements

So my issue is, I get a wierd sound problem (it repeats the hit sound really fast) when I use an if statement to determine if I hit the monster and lived or if I hit the monster and died. Using classic mario logic, if I land on top I live, if not then I die. I didn't have a problem until I added two different if statements. If you need more info let me know. I think my problem is how I am using the if statement.

private void checkGhostCollisions() {
    int len = ghosts.size();
    for (int i = 0; i < len; i++) {
        Ghost ghost = ghosts.get(i);
        if (hero.position.y < ghost.position.y) {
            if (OverlapTester.overlapRectangles(ghost.bounds, hero.bounds))
                hero.hitGhost();
                listener.hit();
        } else {
        if(hero.position.y > ghost.position.y) 
             if (OverlapTester.overlapRectangles(hero.bounds, ghost.bounds)) {
                 hero.hitGhostJump();
                 listener.jump();
            break;
            }
        }
    }
}

Upvotes: 0

Views: 3435

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503439

I suspect this is the problem:

if (hero.position.y < ghost.position.y) {
    if (OverlapTester.overlapRectangles(ghost.bounds, hero.bounds))
        hero.hitGhost();
        listener.hit();
}

Note the lack of braces for the inner if statement, meaning that if the first if condition is satisfied, listener.hit() is always called. I suspect you meant:

if (hero.position.y < ghost.position.y) {
    if (OverlapTester.overlapRectangles(ghost.bounds, hero.bounds)) {
        hero.hitGhost();
        listener.hit();
    }
}

Two lessons to learn from this:

  • Always indent your code properly, and get your IDE to indent it for you if you get confused.
  • If you always use braces with if blocks, it reduces the opportunity for this kind of thing to occur.

EDIT: Note that the inner if condition in each case is the same, which means you could simplify this code to:

if (OverlapTester.overlapRectangles(hero.bounds, ghost.bounds)) {
    if (hero.position.y < ghost.position.y) {
        hero.hitGhost();
        listener.hit();
    } else {
        hero.hitGhostJump();
        listener.jump();
        break;
    }
}

Note that this does slightly change the case where hero.position.y is exactly the same as ghost.position.y - you should consider what you want to happen in that case.

Upvotes: 9

Related Questions