很多精灵都在屏幕上

很多精灵都在屏幕上

本文介绍了Java Swing的游戏表现不佳时,很多精灵都在屏幕上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我做了一个Swing简单的塔防游戏,我已经当我试图把许多精灵(超过20),在屏幕上遇到性能问题。

整场比赛呈现出的JPanel有setIgnoreRepaint(真)的地方。
下面是paintComponent方法(con是控制器):

 公共无效的paintComponent(图形G){
    super.paintComponent方法(G);
    //绘制网格
    g.drawImage(背景,0,0,NULL);
    如果(CON!= NULL){
        //绘制塔
        对于(塔T:con.getTowerList()){
            t.paintTower(G);
        }
        //绘制目标
        如果(con.getTargets()。大小()!= 0){
            (目标T:con.getTargets()){
                t.paintTarget(G);
            }
            //绘制镜头
            对于(射击小号:con.getShots()){
                s.paintShot(G);
            }
        }
    }
}

目标类的简单的油漆在其当前位置的BufferedImage。该getImage方法不会创建一个新的BufferedImage,它只是返回它的控制器类的实例:

 公共无效paintTarget(图形G){
    g.drawImage(con.getImage(目标),为getPosition()x - 20为getPosition()Y - 20,空);
}

每个目标上运行一个Swing计时器来计算其位置。这是它调用的ActionListener:

 公共无效的actionPerformed(ActionEvent的五){
    如果(!waypointReached()){
        X + = DX;
        Y + =颐;
        con.repaintArea((INT)x - 25,(INT)Y - 25,50,50);
    }
    其他{
        移动= FALSE;
        mover.stop();
    }
}私人布尔waypointReached(){
    返回Math.abs(X - currentWaypoint.x)LT =速度和安培;&安培; Math.abs(Y - currentWaypoint.y)LT =速度;
}

除此之外,重绘()将新塔时,只调用了。

我怎样才能提高性能?​​


解决方案

This may be your problem - having each target/bullet (I assume?) responsible for keeping track of when to update itself and draw itself sounds like quite a bit of work. The more common approach is to have a loop along the lines of

while (gameIsRunning) {
  int timeElapsed = timeSinceLastUpdate();
  for (GameEntity e : entities) {
    e.update(timeElapsed);
  }
  render(); // or simply repaint in your case, I guess
  Thread.sleep(???); // You don't want to do this on the main Swing (EDT) thread though
}

Essentially, an object further up the chain has the responsibility to keep track of all entities in your game, tell them to update themselves, and render them.

这篇关于Java Swing的游戏表现不佳时,很多精灵都在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:03