2013-01-21 2 views
0

튜토리얼을 통해 제작되는 게임의 기본 클래스입니다. 스레드가 무엇인지, 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; 
    } 
} 

답변

1

루프는 while(running) 루프에서 발생합니다.

기본적으로 delta 변수는 누적 기이며, tick()이 호출 된 이후 경과 한 시간을 추적합니다. 루프가 실행될 때마다 delta을 업데이트하여 루프가 마지막으로 실행 된 이후 경과 한 시간을 추가합니다. 루프가 실행되는 빈도보다 빠르게 실행될 수 있으므로 tick()입니다.

충분한 시간 (delta>=1), tick()이 실행되면 누적 기 delta이 재설정되고 프로세스가 다시 시작됩니다.

이것은 기본 루프의 기본 구현입니다. 기본적으로 1 초에 60 프레임으로 실행을 중단합니다 ...하지만 주 루프가 느려지고 1 초에 60 회 이상의 실행을 수행 할 수없는 경우 게임 플레이도 시각적으로 느려집니다.

메인 루프의 다른 예제는 Glenn Fiedler's excellent Fix Your Timestep! article on this subject을 확인하십시오.

관련 문제