我是Java的新手,并尝试编写自己的小gameloop
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
答案 0 :(得分:0)
您要增加游戏的睡眠时间,具体取决于游戏逻辑需要多长时间。您要做的是根据游戏逻辑所需的时间减少睡眠时间。
您还需要在计算中包括渲染时间(在很多游戏中,渲染时间可能会很快大于游戏逻辑时间)。尝试这样的事情:
long delta, end, start = System.currentTimeMillis();
while (running) {
runtick();
runrender();
end = System.currentTimeMillis();
delta = (end - start);
Thread.sleep((1000 / fps) - delta);
start = end;
}
如果您发现delta
大于滴答间隔(1000 / fps)
,则应记录一些警告,为缓解这种情况,您可以为每个渲染滴答运行多个游戏逻辑滴答,以使游戏逻辑可以赶上动画。