2011-01-14 5 views
2

XNA 私はボタンクラスを持っていて、現在のゲーム状態(メインメニュー)に応じてどのボタンを画面に描画するかを管理するbuttonManagerクラスを持っています、ゲーム中など)、ボタンをクリックすると、ユーザーが別の画面に移動するように、コードを整理するにはどうすればいいですか? (例えば、オプションメニュー、ingame)。 具体的には、ユーザーがbuttonManager内のボタンをクリックしたかどうかを確認するには、ゲームを切り替えて実際のゲーム(別のクラス全体にあります)を実行するにはどうすればよいですか?XNAゲームコンポーネント(マネージャ)でコードを整理する方法

  • メインgameclass
  • buttonManagerゲームコンポーネント(ボタンが追加されます)
  • それを行うのButtonクラス

答えて

2

一つの方法は、デリゲートを使用することです。別の方法は、すべてのクラスが状態を決定するために使用するグローバルクラスを持つことです。

あなたがゲームの状態の概念に慣れていない場合、私は基本的にあなたを緩和私のサイトのチュートリアルを持っている(とそのチュートリアルの最後のサンプルは、同様に、デリゲートを使用しています!)

http://www.xnadevelopment.com/tutorials/thestateofthings/thestateofthings.shtml

+0

+1:これは私がそれを行う方法であり、値をハードコーディングせずにエンジンを再利用できるということです。 –

0

あなたのスクリーンクラス(menuScreen、optionsScreen、gameplayScreenなど)は、表示される各ボタンの機能を保持する必要があります。例:

//in optionsScreen class' update method: 
if(input.gamepad.Buttons.A == ButtonState.Pressed && cursorSpriteRect.Intersects(button[0].Rect) 
{ 
    //begin transition into gameplay screen... or whatever 
} 
0

ゲームにボタンマネージャーがあるか、またはボタンマネージャーへの参照が必要です。通常、あなたのゲームはbuttonManagerを作成し所有します。

class Game 
{ 
    ButtonManager m_buttonManager; 

    ... 
} 

ボタンマネージャは、OnButtonClickedのようなイベントを公開することができます。

class ButtonManager 
{ 
    private Button m_playGameButton; 

    // delegate to define the type of the event handler 
    public delegate void ButtonClickedEventHandler(ButtonId buttonId); 

    // event object matching the type of the event handler 
    public event ButtonClickedEventHandler OnButtonClicked; 

    void Update() 
    { 
     ... 

     if (m_playGameButton.Clicked) 
     { 
     // Launch the event when appropriate if there are any subscribers 
     if (OnButtonClicked != null) 
     { 
      OnButtonClicked(ButtonId.PlayGame) 
     } 
     } 
    } 
} 

ゲームクラスは、イベントに登録してハンドラメソッドを提供できます。

class Game 
{ 
    ... 

    void Initialise() 
    { 
     m_buttonManager += ButtonClicked; 
    } 

    void ButtonClicked(ButtonId buttonId) 
    { 
     switch (buttonId) 
     { 
      case ButtonId.PlayGame: 
       PlayGame(); 
       break; 

      case ButtonId.OptionsMenu: 
       OptionsMenu(); 
       break; 
     } 
    } 

    ... 
} 

また、ゲームクラスはボタンマネージャをポーリングできます。

class Game 
{ 
    ... 

    void Update() 
    { 
     if (m_buttonManager.IsPlayGameButtonHit) 
     { 
     PlayGame(); 
     } 
     else if (m_buttonManager.IsOptionsMenuButtonHit) 
     { 
     OptionsMenu(); 
     } 
    } 

    ... 
} 
関連する問題