2016-11-27 69 views
0

目前,我的代碼正在生成的蜱數量有問題。我目前正沿着一個視頻遊戲指南,用於更新邏輯的刻度數量要比它們都應該在60上時要高出幾倍。這是YouTube視頻 https://www.youtube.com/watch?v=VE7ezYCTPe4&t=1358s 任何建議將不勝感激。先進的謝謝!爲什麼我的java代碼不限制這些數字?

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(); 
} 

}

回答

0

在你while(delta >= 1){循環,你實際上會增加蜱。鑑於完美的系統,該增量應該大約爲16666667ns,因此每個增量可能有16666667個滴答。我對你的教程非常好奇,因爲通常你會在系統中使用delta(比如物理)而不是循環。如果你想獲得有關Java遊戲開發的資源,我強烈推薦檢查https://www.lwjgl.org/,更不要說大量關於博客的文章了。話題。