我有以下代码:
public class Screen {
...// more code
private int width, height;
public int[] pixels;
public void render(int xOffSet, int yOffSet) {
for (int y = 0; y < height; y++) {
int yPix = y + yOffSet;
if (yPix < 0 || yPix >= height)
continue;
for (int x = 0; x < width; x++) {
int xPix = x + xOffSet;
if (xPix < 0 || xPix >= width)
continue;
pixels[(xPix) + (yPix) * width] = Sprite.grass.pixels[(x & Sprite.grass.SIZE - 1)
+ (y & Sprite.grass.SIZE - 1) * Sprite.grass.SIZE];
}
}
}
这基本上会在屏幕上呈现许多相同的16x16图块。
然后我有这两种方法(在一个线程中循环)
public class Game extends Canvas implements Runnable {
...//more code
public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0; // Nanosegundos necesarios para
// correr el juego a 60fps
double delta = 0;
int frames = 0;
int updates = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
frame.setTitle(title + "\t \t FPS: " + frames + " UPS: " + updates + ".");
frames = updates = 0;
}
}
stop();
}
public int x = 0, y = 0;
public void tick() {
keyboard.tick();
if(keyboard.up) y--;
if(keyboard.down) y++;
if(keyboard.left) x--;
if(keyboard.right) x++;
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.clear();
screen.render(x, y);
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
}
更新并重新渲染屏幕。
我的问题是,当我按任意键,移动屏幕时,看起来图像是“闪烁”,不会立即更新(游戏运行速度约为1000 fps,每秒60次)。有没有简单的方法来解决这个问题?