2017-03-04 103 views
2

我剛開始創建Android遊戲,並決定從Retro Chicken的教程開始。遊戲究竟在哪裏開始?

我只是沒有得到的是遊戲真正開始聽命令的地方? 通常他們有一個功能,如public void run()被調用。 主要是這樣的:

game = new GamePanel(this); 
setContentView(game); 

,並呼籲主要的構造函數是:

public GamePanel(Context context){ 
    super(context); 
    this.getHolder().addCallback(this); 
    thread = new MainThread(getHolder(), this); // Inherits [Thread] class. Code posted 

    player = new RectPlayer(new Rect(100,100,200,200), Color.rgb(255,0,0)); Class made by me. Has nothing special. 
    playerPoint = new Point(150,150); 
    // We ensure that THIS canvas will get the focus. 
    setFocusable(true); 
} 

我通過一些super調用衝浪,但仍沒有

  1. MainThread.java
  2. GamePanel.java

    編輯:我感興趣什麼叫run函數,在哪裏以及如何?

回答

3

這是真正開始控制線程塊,

@Override 
public void surfaceCreated(SurfaceHolder holder){ 
    thread = new MainThread(getHolder(), this); 
    thread.setRunning(true); 
    thread.start(); 
} 

由於class MainThread extends Thread,調用Thread對象的start方法將調用一個新的線程run方法。

現在該方法如何運行?

@Override 
public void surfaceCreated 

這是implements SurfaceHolder.Callback定義的覆蓋。

game對象知道有關接口,因爲構造的傳遞本身到保持器,本身的引用,包含接口被調用。

this.getHolder().addCallback(this); 

持有人現在有這個類的引用,並可以調用

callback.surfaceCreated(); 

哪裏surfaceCreated是你實現的接口方法。

現在怎麼表面獲得創建?

The surfaceCreated method is called when

這被稱爲後立即在首次創建表面。這個實現應該啓動他們想要的任何渲染代碼。請注意,只有一個線程可以繪製到Surface中,因此如果您的普通渲染將位於另一個線程中,則不應在此處繪製Surface。

您通過調用最終致電setContentView(game);來啓動該過程,使表面膨脹。

+0

所以,基本上,'surfaceCreated'是啓動所有的方法之一。謝謝,這就是我一直在尋找的! – SnuKies

+0

'surfaceCreated'包含的代碼,啓動遊戲線程塊,但只叫,因爲你'的setContentView(遊戲);',如果你要創建的遊戲對象,但從來沒有把它添加到視圖,該線程將永遠不會開始。你不應該直接調用它,而是應該調用層次結構,否則最終會出現多個流氓線程。 –

0

有了Android,你必須創建一個包含您的按鈕,面板,觀點...佈局(XML文件),那麼你線了該佈局到你的java文件。

0

這裏是主線程獲取startet的地方,如果它是你想知道的。

@Override 
public void surfaceCreated(SurfaceHolder holder){ 
    thread = new MainThread(getHolder(), this); 
    thread.setRunning(true); 
    thread.start(); 
} 

我想你應該指出你的問題一點點。

這裏是回調方法,它處理遊戲面板上的觸摸。

@Override 
public boolean onTouchEvent(MotionEvent event){ 
    /* [event.getAction()] : returneaza un [int] care are o valoeare 
     in functie de ce fel de touch e 
    */ 
    switch (event.getAction()){ 
     case MotionEvent.ACTION_DOWN: 
     case MotionEvent.ACTION_MOVE: 
      playerPoint.set((int)event.getX(), (int)event.getY()); 

    } 
    return true; 
} 
+0

但是,在被調用該函數?這就是讓我困擾 而在'MainThread'類,有一個'公共無效的run()'基本上在遊戲開始時,如果我沒有錯。什麼叫這個功能? – SnuKies

+0

線程對象在調用start()方法時內部調用run()方法。 這裏做進一步的瞭解: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html – Screwb

0

GamePanel類是SurfaceView,提供繪圖表面。您正在通過setContentView(game);添加一個圖層。

現在您需要開始繪製。在繪圖中,如果需要更改Paint Board(表面視圖)中的某些內容,則需要再次擦除和繪製。

現在您需要再次撥打draw (Canvas canvas)才能達到上述目的。所以你使用MainThread。

看看你的run()你的MainThread的方法,有一個無限的while(true)循環。通過該循環,您的GamePanel的draw (Canvas canvas)在特定的時間段內運行呼叫。