Alc*_*hms 3 java animation swing
我正在Swing中制作一个简单的塔防游戏,当我尝试在屏幕上放置许多精灵(超过20个)时,我遇到了性能问题.
整个游戏发生在具有setIgnoreRepaint(true)的JPanel上.这是paintComponent方法(con是Controller):
public void paintComponent(Graphics g){
super.paintComponent(g);
//Draw grid
g.drawImage(background, 0, 0, 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Target类simple在其当前位置绘制BufferedImage.getImage方法不会创建新的BufferedImage,它只返回Controller类的实例:
public void paintTarget(Graphics g){
g.drawImage(con.getImage("target"), getPosition().x - 20, getPosition().y - 20, null);
}
Run Code Online (Sandbox Code Playgroud)
每个目标都运行一个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;
}
Run Code Online (Sandbox Code Playgroud)
除此之外,只在放置新塔时调用repaint().
如何提高性能?
每个目标都运行一个Swing Timer来计算它的位置.这是它调用的ActionListener:
这可能是你的问题 - 让每个目标/子弹(我假设?)负责跟踪何时更新自己并绘制自己听起来像是相当多的工作.更常见的方法是沿着线路循环
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
}
Run Code Online (Sandbox Code Playgroud)
从本质上讲,链上的一个对象有责任跟踪游戏中的所有实体,告诉他们自己更新并渲染它们.