我目前正在完全用Java开发游戏。到目前为止,我的主循环正在以“执行动作”方法运行,该方法由计时器每100秒更新一次。在该循环中,代码重新绘制并针对玩家位置,敌方位置等进行了一堆数学运算。我的代码运行正常,并且在我的2009年中期的Macbook Pro上没有太多滞后,并且奇怪的是,我的代码运行得非常糟糕(非常)新的Surface Pro 4(非常出色的机器)。它还可以在我的(AMD)台式PC上很好地运行。我使用VisualVM和任务管理器运行了一些诊断程序和示例,虽然它不占用很多机器资源,但在Surface Pro上,它以4或5 FPS的速度运行,这主要是由于我的绘画组件所致。我的pain(t)组件非常庞大,其中包含大量循环,用于数组列表中的粒子,数组列表中的敌人,数组列表中的敌人粒子等。所有这些都需要绘制。 (它们会随着时间的推移而被删除,所以这不是问题)。为什么我的旧Macbook在运行此程序方面比我的新朋友Surface Pro好得多?有没有更好的方法来运行代码? Github链接在这里:https://github.com/gkgkgkgk/JetGame谢谢!
(此外,如果可以的话,请在您的计算机上对其进行测试,并让我知道它的运行方式!)

这是我的最小的可验证代码:

public class Test extends JPanel implements KeyListener {
JFrame w;

Timer t = new Timer();


double elapsedTime = 0.016;

public Test() {
    w = new JFrame();
    w.setSize(1280, 720);
    w.setContentPane(this);
    w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    w.addKeyListener(this);
    w.setResizable(false);
    w.setVisible(true);
    loop();

}

public void loop() {
    t.scheduleAtFixedRate(new TimerTask() {
        public void run() {

            //does calculations
            repaint();

        }
    }, 0, 16);
}





public void keyPressed(KeyEvent e) {
    //booleans are set to true and falso for movement in these methods

}
public void keyReleased(KeyEvent e) {



}
public void keyTyped(KeyEvent e) {}




public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g.
    //painting is done in a bunch of nested for loops here

}

void calculateFPS(long x) {
    System.out.println(1000 / (System.currentTimeMillis() - x) + "FPS");
}
public static void main(String[] args) {
    new Test();
}


}

最佳答案

您应该尝试创建自己的游戏循环,而不依赖于util Timer。

在线上有许多示例,介绍了如何编写有效的示例。


http://www.java-gaming.org/index.php?topic=24220.0
https://github.com/SilverTiger/lwjgl3-tutorial/wiki/Game-loops(本教程适用于LWJGL,但我真的很喜欢)
https://lwjglgamedev.gitbooks.io/3d-game-development-with-lwjgl/content/chapter2/chapter2.html(这也是LWJGL,但是算法应该相同)

09-30 17:35
查看更多