我对java很新。
我试图通过观看在线教程来使用java语言制作游戏。在我的代码中,我有一个游戏循环,它调用render方法来显示我想要显示的游戏对象。但是出于某种原因,我的代码似乎不像在线教程描述的那样工作。
以下是我迄今为游戏开发编写的代码。
游戏类
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 = 1902147405213257243L;
public static final int WIDTH = 640, HEIGHT = WIDTH/12*9;
private Thread thread;
private boolean running = false;
public Game() {
new Window(WIDTH, HEIGHT, "Practice Game", this);
}
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() {
}
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);
g.dispose();
bs.show();
}
public static void main(String[] args) {
new Game();
}
}
窗口类
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Window extends Canvas {
public Window (int width, int height, String title, Game game) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.add(game);
game.start();
}
}
此代码的问题是框架的背景颜色仍然是默认颜色,而不是呈现黑色背景。
我还注意到,使用三重缓冲运行游戏导致打印FPS大约800,000,而使用双缓冲导致2,000个奇怪的原因。
我正在使用eclipse和java版本8.我正在使用mac。