游戏循环不起作用

时间:2016-07-22 11:26:23

标签: java multithreading game-loop

boolean running = false;
Rectangle rect = new Rectangle(10, 10, 80, 80);
JButton b = new JButton("Misca-te!");;
boolean shouldClearRect = false;
String path = new String();
BufferedImage i;
int x = 0;
double a = x;
boolean q = true;
public Thread th;

public void paintComponent(Graphics g){
    super.paintComponent(g);
    this.setBackground(Color.RED);

    g.drawImage(i, x, 0, null);
    path = "/Xture/apple.png";
    i = game2.loadImage(path);
    this.add(b);    
}

public void update(){
    x+= 1;
}

public void run(){
    int fps = 60;
    double timepertick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lasttime = System.nanoTime();
    long timer = 0;
    int ticks = 0;

    while(true){
        now = System.nanoTime();
        delta += (now - lasttime)/ timepertick;
        timer += now - lasttime;
        lasttime = now;

        if(delta >= 1){
            update();
            ticks++;
            delta--;
        }
        if(timer >= 1000000000){
            System.out.println(ticks);
            ticks = 0;
            timer = 0;
        }
    }
}

public void start(){
    running = true;
    th = new Thread(this);
    th.start();
}

public static BufferedImage loadImage(String path){
    try {
        return ImageIO.read(game2.class.getResource(path));
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
    return null;
}

此代码需要每秒移动1个像素。但是如果我运行它,它一次移动超过1个像素然后停止,然而每秒它在控制台中写入“60 fps”。我的代码有问题,还是笔记本电脑有问题?

P.S。:JFrame在主类

1 个答案:

答案 0 :(得分:0)

我认为如果你这样做会更简单:

public void run(){
    int fps = 1;
    double delay = 1000 / fps;
    int ticks = 0;
    while(true){
        delay();
        update();
        System.out.println(++ticks);
    }   
}

public void delay(int mil){
    try{
        Thread.Sleep(mil);
    }catch(Exception e){

    }
}