2012-06-11 3 views
0

내 문제는, 나는 괴물을 치고 몬스터를 치고 죽었는지 결정하기 위해 if 문을 사용할 때 wierd 사운드 문제를 일으킨다. . 고전적인 마리오 논리를 사용하여, 내가 위에 얹어 놓으면 나는 살고, 그렇지 않다면 나는 죽는다. 두 개의 다른 if 문을 추가 할 때까지는 문제가 없었습니다. 더 많은 정보가 필요하시면 알려주세요. 내 문제는 if 문을 사용하는 방법이라고 생각합니다.android 만약 else 문을

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

주 최초의 if 조건이 만족 될 경우, listener.hit() 항상 라는 것을 의미 내부if 문에 대한 괄호의 부족 : 나는 의심

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; 
      } 
     } 
    } 
} 
+0

hero.position == ghost.position이란 무엇입니까? – Blundell

답변

9

이 문제입니다 .

  • 항상 제대로 코드 들여 쓰기, 그리고 당신이 혼란스러워하는 경우 당신을 위해 그것을 들여 당신의 IDE를 얻을 :이 배울 수

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

    두 가지 교훈을 : 당신이 의미 생각한다.

  • 항상 블록을 사용하여 중괄호를 if 블록으로 사용하면 이러한 문제가 발생할 가능성이 줄어 듭니다.

편집 :이 약간 hero.position.y 정확히 인 경우 변경 않습니다

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

참고 :이 코드를 단순화 할 수있는 의미, 각각의 경우에 내부 if 조건이 동일합니다 ghost.position.y과 동일합니다. 그런 경우에 무엇을하고 싶은지 고려해야합니다.

+0

지금과 같은 경우 (hero.position.y> ghost.position.y) { \t \t "무시하는 경우 (OverlapTester.overlapRectangles (hero.bounds, ghost.bounds)) { \t \t hero.hitGhostJump(); \t \t listener.jump(); " – user1449547

+0

@ user1449547 : 각각의 경우에 당신이 원하는 일을 정확히 내게 알려주지는 않습니다 ... 당신은 효과적으로 4 가지 가능성을 얻었습니다. 각각의 경우에 무엇을하고 싶니? –

관련 문제