gpt4 book ai didi

java - 为什么这个游戏循环滞后?

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:02 24 4
gpt4 key购买 nike

我对 Java 完全陌生,并尝试编写自己的小游戏循环

package com.luap555.main;

import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.Timer;

public class Game implements Runnable{

private Window window;
public int width, height;
public String title;

private boolean running = false;
private Thread thread;

private BufferStrategy bs;
private Graphics g;

private int fps = 60;
private long lastTime;
private long now;
private long delta;
private long timer;
private long ticks;
private boolean initialized = false;

public Game(String title, int width, int height) {
this.title = title;
this.width = width;
this.height = height;

}

private void init() {
window = new Window(title, width, height);
Assets.init();
System.out.println("Initializing finished");
initialized = true;
}

private int x = 0;

private void tick() {
x += 1;

}

private void render() {
bs = window.getCanvas().getBufferStrategy();
if(bs == null) {
window.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();

g.clearRect(0, 0, width, height);

g.drawImage(Assets.unten, 0 + x, 0, 700, 350, null);

bs.show();
g.dispose();
}

private void runtick() {
lastTime = System.currentTimeMillis();

tick();

now = System.currentTimeMillis();
delta += now - lastTime;

try {
Thread.sleep((delta + 1000) / fps);
} catch (InterruptedException e) {
e.printStackTrace();
}

delta -= now - lastTime;
}

private void runrender() {
render();
}

@Override
public void run() {
init();

if(initialized) {
while(running) {
runtick();
runrender();
}
}

stop();

}

public synchronized void start() {
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();

}

public synchronized void stop() {
if(!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

在我的主要方法中,我调用 game.start() 方法。但每当我运行这段代码时,图片的移动就相当滞后。我的移动相当流畅,但每隔一秒左右就会出现一些滞后。我认为问题出在“runtick()”方法中。有谁知道为什么会发生这种情况?我希望你们中的一些人可以帮助我;D

最佳答案

您将根据游戏逻辑所需的时间来增加游戏的 sleep 时间。您想要做的是根据游戏逻辑所需的时间来减少 sleep 。

您还需要将渲染时间纳入您的计算中(在很多游戏中,这很快就会变得比游戏逻辑时间长)。尝试这样的事情:

long delta, end, start = System.currentTimeMillis();
while (running) {
runtick();
runrender();

end = System.currentTimeMillis();
delta = (end - start);
Thread.sleep((1000 / fps) - delta);
start = end;
}

如果您发现delta变得大于tick间隔(1000/fps),那么您应该记录一些警告,并为了缓解这种情况,您可以在每个渲染tick中运行多个游戏逻辑tick,以允许游戏逻辑 catch 动画。

关于java - 为什么这个游戏循环滞后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53145267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com