我是 Java 游戏编程的新手,但我的游戏遇到了问题。我正在为我在学校的班级和乐趣做这个,所以我从学校的电脑和家里的电脑转移我的代码。
最近,当我在家里运行我的程序时,窗口闪烁非常快,我不知道发生了什么。我使用缓冲策略并测试了一些值,但没有任何变化。当我在学校计算机上运行代码时,它运行良好。
我想知道我的问题是否实际上是缓冲策略,或者我的 Nvidia 显卡对我的显示器有什么影响。
我还录制了显示“闪烁”的屏幕,因此您可以在此 YouTube 视频中看到我在说什么。
这是我使用缓冲策略的游戏类。
public class Game implements Runnable{
public int width, height;
public String title;
private Display display;
private BufferStrategy bs;
private Graphics g;
private Thread thread;
private boolean running = false;
//States
private State menuState;
private State gameState;
//Input
private KeyManager keyManager;
public Game(String title, int width, int height){
this.title = title;
this.width = width;
this.height = height;
keyManager = new KeyManager();
}
private void init(){
display = new Display(title, width, height);
display.getFrame().addKeyListener(keyManager);
Assets.init();
menuState = new MenuState(this);
gameState = new GameState(this);
State.setState(menuState);
}
private void update(){
keyManager.update();
if(State.getState() != null){
State.getState().update();
}
}
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
display.getCanvas().createBufferStrategy(1);
return;
}
g = bs.getDrawGraphics();
// Clear
g.clearRect(0, 0, width, height);
// Draw
if(State.getState() != null){
State.getState().render(g);
}
// End Draw
bs.show();
bs.dispose();
}
public void run() {
init();
int fps = 60;
double timePerTick = 1000000000 / fps; // 1 second (in nanoseconds)
double delta = 0;
long now;
long lastTime = System.nanoTime();
long timer = 0;
int ticks = 0;
while (running){
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += now - lastTime;
lastTime = now;
if(delta >= 1){
update();
render();
ticks++;
delta--;
}
if(timer >= 1000000000){
System.out.println("Ticks and frames:" + ticks);
ticks = 0;
timer = 0;
}
}
stop();
}
public synchronized void start(){
if (running)
return;
running = true;
thread = new Thread(this);
thread.start(); // Call run()
}
public synchronized void stop(){
if (!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public KeyManager getKeyManager(){
return keyManager;
}
}