2015-12-14 51 views
0

遊戲循環:Java圖像出現和消失使用遊戲循環時

private int FPS = 25; 
private int targetTime = 1000/FPS; 

public void run(){ 

    init(); 

    long start; 
    long elapsed; 
    long wait; 

    while (running){ 

     start = System.nanoTime(); 
     init(); 
     repaint(); 
     elapsed = System.nanoTime() - start; 

     wait = targetTime - elapsed/1000000; 

     try { 

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

    } 
} 

paint方法:

/**draws the game graphics*/ 
public void paint(Graphics g){ 
    super.paint(g); 
    Graphics2D g2 = (Graphics2D)g; 

    gameStateHandler.draw(g2); 

} 

方法的paint方法是指太:

private static Image image = resourceLoader.getImage("/background/menu_background.png"); 
/**draws the menu state*/ 
public static void draw(Graphics2D g){ 

    g.drawImage(image, 0, 0, null); 
} 

我所說的圖像從該方法,該方法是在圖像

static resourceLoader rl = new resourceLoader(); 

public static Image getImage(String image){ 

    return Toolkit.getDefaultToolkit().getImage(rl.getClass().getResource(image)); 
} 

我有一個遊戲循環,它將調用每秒和在油漆方法repaint(); 60倍它指的是一種方法,其中的相同的文件夾此方法繪製圖像。一切看起來不錯,順利,當我運行該程序的圖像出現,並在快速消失,有時圖像出現,沒有什麼不好發生,但經過一段隨機時間的事情發生我把fps從低到高,從高到低仍然相同即時通訊使用jpanel在這個項目中

+1

你的'圖像'在哪裏創建/操作? – JimmyB

+0

聽起來像缺乏雙緩衝http://content.gpwiki.org/index.php/Java%3aTutorials%3aDouble_Buffering – weston

+0

@weston也是這麼想的,但是將圖像傳遞給畫布應該像更新一樣快顯示器。 – JimmyB

回答

0

好了,所以這裏有一個建議,這很可能是你所需要的修復:

使用paintComponent()而不是paint()

// draws the game graphics 

@Override 
public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g;  
    gameStateHandler.draw(g2);  
} 

paintComponentrecommended way to use JPanels to paint in Java - 又見a more detailed explanation of custom painting in Swing。這很可能是因爲你使用paint()是造成視覺不一致的原因。

如果沒有,我建議看看你是如何加載你的資源,但這應該工作,所以我不認爲這是問題。

+0

好的謝謝,但你怎麼稱呼它在gameloop?對不起,我是一個新的程序員@Gorbles – Heroxlegend

+0

當你調用'repaint()'時,應該由Swing調用它 - 它應該自動完成。 – Gorbles

0

不要使用Thread.sleep()。如果在EDT上調用,可能會導致口吃。

對於擺動,您應該使用javax.swing.Timer:
1.使用所需的延遲(您的targetTime)初始化Timer。
2.在timer actionPerformed()調用repaint()。

+0

'Thread.sleep()* *可能會導致口吃,但不會推定您的目標幀率是可以接受的。當然,在屏幕上繪製一個圖像不會在模糊的現代硬件上造成不必要的延遲,特別是在25FPS的目標速率下。不幸的是,我不確定你的建議會對你有幫助。 – Gorbles

0

在你的遊戲循環,之後

wait = targetTime - elapsed/1000000; 

添加一行

wait = Math.max(5L, wait); 

,讓您的等待時間變得過小或變負。

+0

它沒有解決問題@Gilbert le blanc – Heroxlegend