튜토리얼을 통해 제작되는 게임의 기본 클래스입니다. 스레드가 무엇인지, while 루프가 무엇인지 이해하지만 이해할 수없는 것은 코드가 게임의 업데이트를 제한하고 실행 방법에서 발견되는 방식입니다.누군가가 러닝 방법에서 일어난 일을 이해하도록 도와 줄 수 있습니까?
package pkg2.pkg5d;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public int height = 300;
public int width = height/16 *9;
public int scale = 3;
public static volatile boolean running = false;
private JFrame frame;
public static void main(String[] args) {
new Main().Start();
}
public Main(){
frame = new JFrame();
setMinimumSize(new Dimension(height*scale,width*scale));
setMaximumSize(new Dimension(height*scale,width*scale));
setPreferredSize(new Dimension(height*scale,width*scale));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void tick(){
}
public void render(){
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000d/60d;
int frames = 0;
int ticks = 0;
double delta = 0;
long lastTimer = System.currentTimeMillis();
while(running){
long now = System.nanoTime();
delta +=(now - lastTime)/ nsPerTick;
lastTime = now;
boolean shouldRender = true;
while (delta>=1){
ticks++;
tick();
delta-=1;
shouldRender = true;
}
try{
Thread.sleep(2);
}catch(InterruptedException e){
e.printStackTrace();
}
if (shouldRender){
frames++;
render();
}
if (System.currentTimeMillis()- lastTimer >=1000){
lastTimer += 1000;
System.out.println(ticks +"," + frames);
frames = 0;
ticks = 0;
}
}
}
public synchronized void Start(){
running = true;
Thread game = new Thread(this);
game.start();
}
public void stop(){
running = false;
}
}