为什么我的java代码不限制这些数字?

时间:2016-11-27 03:58:26

标签: java youtube

目前我的代码正在生成的滴答数量存在问题。我目前正在关注一个视频游戏指南,用于更新逻辑的滴答数量指数高于它们应该都停留在60的帧数。这是YouTube视频 https://www.youtube.com/watch?v=VE7ezYCTPe4&t=1358s 任何建议将不胜感激。先谢谢你了!

package game;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;

public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";

private JFrame frame;

public boolean running = false;

public game() {
    setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
    setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
    setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

    frame = new JFrame(NAME);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    frame.add(this,BorderLayout.CENTER);
    frame.pack();

    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

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

}

public synchronized void stop() {
    running = false;

}

public void run() {
    long lastTime = System.nanoTime();
    double nsPerTick = 1000000000 / 60D;

    int ticks = 0;
    int frames = 0;

    long lastTimer = System.currentTimeMillis();
    double delta = 0;

    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTimer) / nsPerTick;
        lastTime = now;
        boolean shouldRender = false;

        while(delta >= 1){
            ticks++;
            tick();
            render();
            delta -= 1;
            shouldRender = true;
        }

        if (shouldRender) {
            frames++;
            render();
            }

        try {
        Thread.sleep(2);
    } catch(InterruptedException e) {
        e.printStackTrace();
    }

        if (System.currentTimeMillis() - lastTimer >= 1000){
            lastTimer += 1000;
            System.out.println(ticks + " ticks, " + frames + " frames");
            frames = 0;
            ticks = 0;
        }
    }


}

public void tick() {
    //updates the logic of the game.

}

public void render() {
    //prints out what the logic says to print out
}

public static void main(String[] args){
    new game().start();
}

}

1 个答案:

答案 0 :(得分:0)

while(delta >= 1){循环中,实际上会增加勾号。鉴于一个完美的系统,该delta应该约为16666667ns,因此每个delta可能有16666667个滴答。我对你的教程非常好奇,因为通常你会在系统中使用delta(比如物理学),而不是在循环中。 tick应该是一个游戏循环,delta用于物理计算等。如果你想要有关Java游戏开发的资源,我强烈建议你查看https://www.lwjgl.org/,更不用说关于这个主题的博客文章。