-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