加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

当许多精灵在屏幕上时,Java Swing游戏的性能很差

发布时间:2020-12-15 05:08:55 所属栏目:Java 来源:网络整理
导读:我正在Swing中制作一个简单的塔防游戏,当我尝试在屏幕上放置许多精灵(超过20个)时,我遇到了性能问题. 整个游戏发生在具有setIgnoreRepaint(true)的JPanel上. 这是paintComponent方法(con是Controller): public void paintComponent(Graphics g){ super.pain
我正在Swing中制作一个简单的塔防游戏,当我尝试在屏幕上放置许多精灵(超过20个)时,我遇到了性能问题.

整个游戏发生在具有setIgnoreRepaint(true)的JPanel上.
这是paintComponent方法(con是Controller):

public void paintComponent(Graphics g){
    super.paintComponent(g);
    //Draw grid
    g.drawImage(background,null);
    if (con != null){
        //Draw towers
        for (Tower t : con.getTowerList()){
            t.paintTower(g);
        }
        //Draw targets
        if (con.getTargets().size() != 0){
            for (Target t : con.getTargets()){
                t.paintTarget(g);
            }
            //Draw shots
            for (Shot s : con.getShots()){
                s.paintShot(g);
            }
        }
    }
}

Target类simple在其当前位置绘制BufferedImage. getImage方法不会创建新的BufferedImage,它只返回Controller类的实例:

public void paintTarget(Graphics g){
    g.drawImage(con.getImage("target"),getPosition().x - 20,getPosition().y - 20,null);
}

每个目标都运行一个Swing Timer来计算它的位置.这是它调用的ActionListener:

public void actionPerformed(ActionEvent e) {
    if (!waypointReached()){
        x += dx;
        y += dy;
        con.repaintArea((int)x - 25,(int)y - 25,50,50);
    }
    else{
        moving = false;
        mover.stop();
    }
}

private boolean waypointReached(){
    return Math.abs(x - currentWaypoint.x) <= speed && Math.abs(y - currentWaypoint.y) <= speed;
}

除此之外,只在放置新塔时调用repaint().

如何提高性能?

解决方法

Each target runs a Swing Timer to calculate its position. This is the ActionListener it calls:

这可能是你的问题 – 让每个目标/子弹(我假设?)负责跟踪何时更新自己并绘制自己听起来像是相当多的工作.更常见的方法是沿着线路循环

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
}

从本质上讲,链上的一个对象有责任跟踪游戏中的所有实体,告诉他们自己更新并渲染它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读