请允许我首先提及我的描述可能不完全可以理解。老实说,我很难找到描述这个问题的词,所以我将我的代码编译成一个可执行的jar,你可能会试图理解我在说什么。
以下是链接:http://www.mediafire.com/download/r1n0ox8ioyzwb2n/WORK.jar
当图像被移动(通过箭头键)到任何方向时,图像将产生奇怪的效果。我只能描述效果,因为从左上角到右下角绘制的图像足够慢,明显可见。如果我不得不猜测我相信它可能与我在游戏循环中正在进行的睡眠有关。这是我的游戏循环和渲染方法。
public void gameLoop() {
final int FPS = 60;
int frames = 0;
lastTime = System.nanoTime();
long lastFPS;
lastTime = lastFPS = System.nanoTime();
init();
while (running) {
long deltaTime = System.nanoTime() - lastTime;
lastTime += deltaTime;
if (!frame.isFocusOwner()||!isFocusOwner())
update(deltaTime);
else{
updateFocus(deltaTime);
}
// Must setup these do-while loops like this according to
// BufferStrategy's Javadoc
render();
// calculate the FPS
frames++;
if (System.nanoTime() - lastFPS >= 1e9) {
fpsValue = frames;
frames = 0;
lastFPS += 1e9;
}
// Gets the remaining number of milliseconds left in the frame
long sleepTime = Math
.round((1e9 / FPS - (System.nanoTime() - lastTime)) / 1e6);
if (sleepTime <= 0)
continue;
// this sleeping method uses Thread.sleep(1) for the first 4/5 of
// the sleep loop, and Thread.yield() for the rest. This gives me an
// accuracy of about 3-4 microseconds
long prev = System.nanoTime(), diff;
while ((diff = System.nanoTime() - prev) < sleepTime) {
if (diff < sleepTime * 0.8)
try {
Thread.sleep(1);
} catch (Exception exc) {
}
else
Thread.yield();
}
sync(60);
}
stop();
}
public void sync(int sync) {
if (sync!=-1) {
long diff = 1000000000L / sync + lastTime;
long now = System.nanoTime();
try {
while (diff > now) {
Thread.sleep((diff-now) / 2000000L);
now = System.nanoTime();
}
} catch (Exception e) {}
lastTime = now;
}
}
public void render() {
BufferStrategy strategy = getBufferStrategy();
if (strategy == null) {
createBufferStrategy(3);
return;
}
do {
do {
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
// draw your game
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
render.setGraphics(g);
// clear the screen
render.clear();
if (sbg != null) {
try {
sbg.renderState(render, g);
// if not focused we draw a focus nagger
if (!frame.isFocusOwner() && !isFocusOwner()
&& sbg.getNagState() != null) {
sbg.getNagState().render(render, g);
}
} catch (VulpusException e) {
e.printStackTrace();
}
}
if (drawFPS) {
g.setColor(Color.white);
g.drawString("FPS: " + fpsValue, 15, 20);
}
g.dispose();
Toolkit.getDefaultToolkit().sync();
} while (strategy.contentsRestored());
strategy.show();
} while (strategy.contentsLost());
}
同步方法允许它实际以60fps运行,否则游戏将运行1000+ fps。如果您有任何想法/建议/需要我澄清一切,请询问。 再次感谢。