我在做简单的2D游戏。我有一个游戏循环,在游戏循环中我有一个更新方法。每当xPos循环时,我就通过向它添加1来移动它。这意味着,如果你有一个慢的fps,那么一切都会以慢动作进行,如果你的fps很高,所有的动作都会非常快。
这是我的密码:
long fpsTimer;
int frames;
public void run(){
running = true;
fpsTimer = System.nanoTime();
while(running){
render();
update();
try{
Thread.sleep(6);
}catch(InterruptedException e){}
frames++;
if(System.nanoTime() >= fpsTimer+1000000000){
System.out.println(frames+" fps");
frames = 0;
fpsTimer = System.nanoTime();
}
}
}全码
import java.awt.*;
import java.awt.image.*;
import javax.swing.JFrame;
import java.awt.event.*;
public class Game extends Canvas implements Runnable{
public static final int WIDTH = 800;
public static final int HEIGHT = 300;
public JFrame f;
private String title = "Untitled Test";
private Image image;
private Sprite player;
public Game(){
player = new Sprite(100, 100);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setMaximumSize(new Dimension(WIDTH, HEIGHT));
setMinimumSize(new Dimension(WIDTH, HEIGHT));
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
player.keyPressed(e.getKeyCode());
}
public void keyReleased(KeyEvent e){
player.keyReleased(e.getKeyCode());
}
});
}
public static void main(String[] args){
Game g = new Game();
g.f = new JFrame(g.title);
g.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.f.add(g);
g.f.setResizable(false);
g.f.pack();
g.f.setLocationRelativeTo(null);
Thread gameLoop = new Thread(g);
gameLoop.start();
g.f.setVisible(true);
}
private void render(){
BufferStrategy bs = getBufferStrategy();
if(bs==null){
createBufferStrategy(3);
return;
}
image = createImage(WIDTH, HEIGHT);
Graphics g = image.getGraphics();
player.draw(g);
g.dispose();
Graphics bsg = bs.getDrawGraphics();
bsg.drawImage(image, 0, 0, WIDTH, HEIGHT, null);
bsg.dispose();
bs.show();
}
private void update(){
player.move();
}
long fpsTime;
int frames;
public void run(){
fpsTime = System.nanoTime();
while(true){
render();
update();
try{
Thread.sleep(6);
}catch(InterruptedException e){}
frames++;
if(System.nanoTime() >= fpsTime+1000000000){
System.out.println(frames+" fps");
frames = 0;
fpsTime = System.nanoTime();
}
}
}
}发布于 2013-11-17 11:38:06
,首先,,你不应该有一个固定的睡眠时间。相反,应该动态计算该值。也许使用Timer#scheduleAtFixedRate(...)更容易,因为这已经为您处理好了。
然后,每次迭代6毫秒似乎太少了。60帧每秒是理想的(如果你只有30,它也好,我认为),所以16毫秒就足够了(或大约32每30 fps)。(请注意,屏幕的刷新速度是上限--应该在60 Hz左右--更多没有意义)。
第三,考虑动态计算对象的移动。与其添加到坐标中的常量增量,不如使用某种“移动函数”,根据当前时间计算坐标。
假设您想以每秒pps像素的恒定速度沿x轴移动一个对象。然后,该对象的x坐标的函数为:
x(t) := x0 + (t - t0) * pps / 1000(t是从ms开始的时间,x0是对象首次出现时的初始x坐标,t0是对象出现的时间,pps是对象每秒移动的像素数)。
这使得你的物体以同样的速度移动--不管你有什么框架。
请注意,如果对象应该对用户输入或其他事件(如冲突等)作出反应,则此方法会变得更加复杂。
https://stackoverflow.com/questions/20029969
复制相似问题