-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 2014-12-06 08:59:38

回答

-1

next()每個呼叫移動迭代器。兩次調用移動它兩次,每次迭代只需要一個元素。如果您想多次使用該值,請緩存該值。

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 
      } 

     } 
    } 

請注意,你也可以做,在實用的風格在Java中8,使用流,雖然這可能是一個初學者矯枉過正。

+0

非常感謝。 我再次爲這個愚蠢的問題感到抱歉。 – SingWithMe 2014-12-06 09:29:44

+0

@SingWithMe沒問題,夥伴,很高興有幫助。 – vaxquis 2014-12-06 09:44:35

+0

親愛的downvoter,你會仔細闡述這個答案的缺陷嗎? – vaxquis 2014-12-16 16:36:45