控制器选择



在我的标题屏幕中,我有一个代码,说第一个使用A的控制器是PlayerIndex.one。这是代码:

    public override void HandleInput(InputState input)
    {
        for (int anyPlayer = 0; anyPlayer <4; anyPlayer++)
        {
            if (GamePad.GetState((PlayerIndex)anyPlayer).Buttons.A == ButtonState.Pressed)
            {
                FirstPlayer = (PlayerIndex)anyPlayer;
                this.ExitScreen();
                AddScreen(new Background());
            }
        }
    }

我的问题是:如何在其他课程中使用"FirstPlayer"?(没有这个,对这段代码就没有兴趣(我尝试了Get Set的东西,但我无法让它工作。我需要将我的代码放在另一个类中吗?您是否使用其他代码来执行此操作?

谢谢。

你可以做一个静态变量说: SelectedPlayer,并为其分配第一个玩家!

然后你可以通过这个类调用第一个玩家,

例如

class GameManager
{
   public static PlayerIndex SelectedPlayer{get;set;}
      ..
      ..
       ..
}

在代码中的循环之后,您可以说:

GameManager.SelectedPlayer = FirstPlayer;

我希望这有所帮助,如果您的代码更清晰,那将更容易帮助:)

好的,所以要正确地做到这一点,你将不得不重新设计一点。

首先,您应该检查新的游戏手柄输入(即,只有在新按下"A"时,您才应该退出屏幕(。为此,您应该存储以前和当前的游戏手柄状态:

    private GamePadState currentGamePadState;
    private GamePadState lastGamePadState;
    // in your constructor
    currentGamePadState = new GamePadState();
    lastGamePadState = new GamePadState();
    // in your update
    lastGamePadState = currentGamePadState;
    currentGamePadState = GamePad.GetState(PlayerIndex.One);

实际上,您需要做的是修改处理输入的类。HandleInput 函数中的基本功能应移动到输入类中。输入应具有测试新输入/当前输入的函数集合。例如,对于您发布的案例:

    public Bool IsNewButtonPress(Buttons buton)
    {
        return (currentGamePadState.IsButtonDown(button) && lastGamePadState.IsButtonUp(button));
    }

然后你可以写:

    public override void HandleInput(InputState input)
    {
        if (input.IsNewButtonPress(Buttons.A)
        {
            this.ExitScreen();
            AddScreen(new Background());
        }
    }

注意:这仅适用于一个控制器。要扩展实现,您需要执行以下操作:

    private GamePadState[] currentGamePadStates;
    private GamePadState[] lastGamePadStates;
    // in your constructor
    currentGamePadStates = new GamePadState[4];
    currentGamePadStates[0] = new GamePadState(PlayerIndex.One);
    currentGamePadStates[1] = new GamePadController(PlayerIndex.Two);
    // etc.
    lastGamePadStates[0] = new GamePadState(PlayerIndex.One);
    // etc.
    // in your update
    foreach (GamePadState s in currentGamePadStates)
    {
        // update all of this as before...
    }
    // etc.

现在,你想要测试每个控制器的输入,所以你需要通过编写一个函数来泛化,该函数在检查数组中的每个 GamePadState 是否按下按钮后返回一个 Bool。

查看 MSDN 游戏状态管理示例,了解开发良好的实现。我不记得它是否支持多个控制器,但结构清晰,如果不可以轻松调整。

最新更新