繁体   English   中英

游戏循环无效

[英]Game loop doesn't work

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”。 我的代码有问题吗,还是我的笔记本电脑有问题?

PS: JFrame在主类中

我认为如果您执行以下操作会更简单:

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){

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM