2016-01-22 29 views
-1

這是我第一次使用JavaFX的遊戲,所以我承認可能做出了一些糟糕的設計決定。無論如何,我想從一個初始頁面(Splash類)過渡到一個過場(Cutscene類),然後到一個可玩水平(PlayableLevel類)。遊戲從我的Main類啓動,並且轉換應該使用鍵盤輸入(Enter按鈕)完成。在JavaFX8中製作遊戲。我如何從Splash頁面切換到Cutscene到Level?

啓動遊戲中主要的方法是這樣的:

public void start (Stage s) { 
     // create your own game here 
     Splash splashPage = new Splash(); 
     Cutscene cs = new Cutscene(); 
     PlayableLevel play = new PlayableLevel(); 
     // attach game to the stage and display it 
     Scene scene0 = splashPage.init(SIZE, SIZE); 
     Scene scene1 = cs.init(SIZE, SIZE, 0); 
     Scene scene2 = play.init(SIZE, SIZE, 0); 
     s.setScene(scene0); 
     s.show(); 

     // sets the game's loop 
     KeyFrame frame = new KeyFrame(Duration.millis(MILLISECOND_DELAY), 
             e -> myGame.step(SECOND_DELAY)); 
     Timeline animation = new Timeline(); 
     animation.setCycleCount(Timeline.INDEFINITE); 
     animation.getKeyFrames().add(frame); 
     animation.play(); 
    } 

我特別的問題是我應該怎麼做才能讓這個飛濺類可以使之與主類溝通一次擊鍵事件被記錄,舞臺可以設置新的場景?我目前正在閱讀有關EventHandlers的內容,但我不確定截至目前的確切實施情況。

編輯:我有一個想法是做一個場景的鏈接列表,然後一旦某個事件發生(按鍵),然後我將場景設置到列表中的下一個。

回答

0

你可以做這樣的事情:

public class Splash { 

    private Runnable nextSceneHandler ; 

    public void setNextSceneHandler(Runnable handler) { 
     nextSceneHandler = handler ; 
    } 

    public Scene init(double width, double height) { 
     Scene scene = new Scene(); 

     // Just an example handler, you could do the same for 
     // button events, menus, etc., or even just handlers for the 
     // end of an animation 
     scene.setOnKeyPressed(e -> { 
      if (nextSceneHandler != null) { 
       if (e.getCode() == ...) { 
        nextSceneHandler.run(); 
       } 
      } 
     } 
     // existing code... 
    } 

    // existing code ... 
} 

,類似的還有CutScene

然後

public void start (Stage s) { 
    // create your own game here 
    Splash splashPage = new Splash(); 
    Cutscene cs = new Cutscene(); 
    PlayableLevel play = new PlayableLevel(); 

    // attach game to the stage and display it 
    Scene scene0 = splashPage.init(SIZE, SIZE); 
    Scene scene1 = cs.init(SIZE, SIZE, 0); 
    Scene scene2 = play.init(SIZE, SIZE, 0); 

    splashPage.setNextSceneHandler(() -> s.setScene(scene1)); 
    cs.setNextSceneHandler(() -> s.setScene(scene2)); 

    s.setScene(scene0); 
    s.show(); 

    // sets the game's loop 
    KeyFrame frame = new KeyFrame(Duration.millis(MILLISECOND_DELAY), 
            e -> myGame.step(SECOND_DELAY)); 
    Timeline animation = new Timeline(); 
    animation.setCycleCount(Timeline.INDEFINITE); 
    animation.getKeyFrames().add(frame); 
    animation.play(); 
} 

你鏈表想法應該工作了。您需要一種機制將鏈接列表實例(或者其迭代器)傳遞給每個場景生成類;他們的事件處理程序將執行代碼的

scene.getWindow().setScene(sceneIterator.next()); 

我有種偏愛設置可運行的對象,感覺有點更靈活。只是一個風格問題。

相關問題