-2

플레이어가 유성우를 쏘고있는 간단한 매끄러운 게임을 개발 중입니다. 두 이미지의 충돌 감지에 문제가 있습니다. 나는 레이저와 유성체에 대해 두 가지 목록을 가지고 있으며, 각 대상은 X와 Y 위치를 가지고 있습니다. 내가하려고하는 것은 현재 이미지 (레이저와 유성체)의 위치를 ​​두 개의 직사각형으로 구현하여 상호 작용 여부를 확인할 수 있고, 그렇게하면 요소가 두 목록에서 삭제됩니다. 내 논리에 문제가있을 수 있으므로 더 일반적인 방법이나 적절한 방법이 있으면 알려 주시기 바랍니다. 여기 java.util.NoSuchElementException 충돌 감지 오류

는 충돌 검출 방법 다음

public void checkCollision(){   

     ListIterator<Shoot> shootItr = shots.listIterator(); 
     ListIterator<Meteor> metItr = meteors.listIterator(); 
     Rectangle2D rectMet; 
     Rectangle2D rectSh; 

     while(shootItr.hasNext()){ 
      rectSh = new Rectangle2D.Float(shootItr.next().getBeamPositionX(), shootItr.next().getBeamPositionY(), 10, 10); 
      while(metItr.hasNext()){ 
       rectMet = new Rectangle2D.Float(metItr.next().getMetPositionX(), metItr.next().getMetPositionY(), 20, 20); 
       if(rectSh.intersects(rectMet)){ 
        metItr.remove(); 
        shootItr.remove(); 
       } 

      } 
     } 
    } 

하는 예외이다

java.util.NoSuchElementException 
    at java.util.ArrayList$Itr.next(Unknown Source) 
+0

한 번에'.next()'를 두 번 호출하고 있습니까? 매 실행마다 값을 저장하십시오. – Emz

답변

-1

next() 각 호출 반복자 이동시킨다. 두 번의 호출은 두 번 반복합니다. 반복 당 하나의 요소 만 필요할 때입니다. 값을 두 번 이상 사용하려면 캐시하십시오. 그건 아마 초보자를위한 잔인한 비록 당신은 또한, 스트림을 사용하여 자바 8에 기능적인 스타일에 있다고 할 수

while(shootItr.hasNext()){ 
     Shoot shoot = shootItr.next(); // cached 
     rectSh = new Rectangle2D.Float(shoot.getBeamPositionX(), shoot.getBeamPositionY(), 10, 10); 
     while(metItr.hasNext()){ 
      Meteor meteor = metItr.next(); // cached 
      rectMet = new Rectangle2D.Float(meteor.getMetPositionX(), meteor.getMetPositionY(), 20, 20); 
      if(rectSh.intersects(rectMet)){ 
       metItr.remove(); 
       shootItr.remove(); 
       break; // otherwise you'll get IllegalStateException if one shot got into two meteors 
      } 

     } 
    } 

참고.

+0

정말 고마워요. 그리고 다시 바보 같은 질문에 대해 유감입니다. – SingWithMe

+0

@SingWithMe 문제 없습니다, 친구, 도움이되어 기쁩니다. – vaxquis

+0

친애하는 downvoter, 당신은이 대답의 부족에 정성 들여 주시겠습니까? – vaxquis