2012-04-08 86 views
2

所以我正在用Java写一个游戏,并且我开始使用drawRect()方法来表示玩家,敌人和镜头。一切都很好。 然后我决定试着去想。 我发现自己创建每个对象的.png图像,并使用Graphics2D drawImage()方法。一切都开始放缓。有没有其他方法可以加快这个过程?Java JPanel动画

我的动画是基于Swing的计时器

public void paint(Graphics g){ 
    super.paint(g); 
    Graphics2D g2d = (Graphics2D)g; 
    player1.paintShips(g); 
    g2d.drawImage(bGround, 14, 14, this); 
    try{ 
     for(Shot s: liveRounds){ //liveRounds is an ArrayList of Shots 
      if(!inBounds.contains(s.getRect()) || villains.collision(s)){ 
       if(villains.collision(s)){ 
        villains.collided(s, this); 
       } 
       liveRounds.remove(s); 
       roundCount--; 
      } 
      else{ 
       s.paintShot(g, this);     
      } 
     } 
    }catch(ConcurrentModificationException e){}; 
    villains.paintEnemyGrid(g, this); 
    g2d.setColor(Color.cyan); 
    g2d.draw(hitZone1); 
    g2d.setColor(Color.red); 
    g.drawString("X: " + player1.getX(1) + " Y: " + player1.getY(1), 370, 150); 
    g2d.draw(inBounds); 
    g.drawString(score + "", 440, 40); 
    g.dispose(); 
} 

动漫任何提示或教程? 谢谢

+0

你的计时器有什么延迟?为什么要捕捉ConcurrentModificationException并忽略它们?如果要在迭代时从“集合”中删除对象,则应该在while循环中手动使用它的'Iterator'并使用'Iterator#remove'。 – Jeffrey 2012-04-08 20:04:26

+0

我把它设置为10,会不会太快? – user1320716 2012-04-08 20:06:04

+2

10毫秒的延迟是每秒100帧。这几乎肯定是太快了。 – Jeffrey 2012-04-08 20:07:31

回答

1

10毫秒的延迟是每秒100帧。这几乎肯定是太快了。

另外,如果你想在你迭代它从Collection删除对象,你需要这样做:

Iterator<T> itr = collection.iterator(); 
while(itr.hasNext()) { 
    T obj = itr.next(); 
    if(removeObj) { 
     itr.remove(); 
    } 
} 

ConcurrentModificationException的领先优势,以不确定性的行为。你需要避开它们,不要忽视它们。