0
我正在嘗試在java中創建我的第一個遊戲,但遇到了一個問題。當我第一次寫我的遊戲循環和FPS計數器我試圖做我自己,但它並不能很好的工作,所以我用這個代碼,我在網上找到:當render()處於活動狀態時計算機凍結
public void run(){
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000/amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}
if(running){
render();
}
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
它的偉大工程,但是當我添加render()函數,該窗口只是一種凍結。我仍然可以關閉窗口,但有時需要重新啓動整個計算機。這是渲染功能。
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.green);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
g.dispose();
bs.show();
}
如果我在渲染功能註釋掉的一切,我得到一個白色的屏幕顯示巫婆我可以隨意移動和一個「常數」 FPS就當周圍16200000.但是在渲染功能的代碼被激活,在FPS看起來是這樣的:
FPS: 8644
FPS: 1
FPS: 5977
FPS: 3189
FPS: 3930
FPS: 8120
FPS: 1
FPS: 8024
FPS: 1
不穩定性或一致性,不要任何人知道我做了什麼錯?我的操作系統是Ubuntu Mate,如果它非常重要,我使用openjdk 1.8.0_91版本。先謝謝你。
完整代碼:
package com.tutorial.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1550691097823471818L;
public static final int WIDTH = 640, HEIGHT = WIDTH/12 * 9;
private Thread thread;
private boolean running = false;
private Handler handler;
public Game(){
new Window(WIDTH, HEIGHT, "Lets Build!", this);
handler = new Handler();
handler.addObject(new Player(100, 100, ID.Player));
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000/amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}
if(running){
render();
}
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
private void tick(){
handler.tick();
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
g.dispose();
bs.show();
}
public static void main(String args[]){
new Game();
}
}
繪圖問題可能在您沒有顯示的Swing代碼中。首先嚐試一個簡單的動畫循環,不要調整渲染處理時間。看看我的[復古蛇遊戲](http://java-articles.info/articles/?p=768)文章,瞭解如何使用動畫循環對Swing應用程序進行編碼。 –
對不起,我錯誤地添加了搖擺,我沒有使用它。刪除了標籤。我仍然會閱讀你的文章,看看我是否可以弄明白,ty! – Salviati