Unity:处理来自多个源(控制器,键盘等)的输入

喜欢这个职位吗? 您可能会喜欢 BentoBlox 也可以-在 App Store 上查看游戏

本周,我将为一款旨在在多个平台上运行的游戏制作原型。 核心挑战之一是预期和处理来自各种不同来源的用户输入。

我的初始方法依赖于Observer-Subscriber模型:单例UserInputDeviceManager存储对当前连接的输入设备(控制器,键盘等)的引用,并在Update上轮询该设备的按钮,以确定是否有任何按钮位于按下状态:

 公共类UserInputDeviceManager:Singleton  
{public UserInputDevice currentUserInputDevice; 公共UserInputDevice []支持的UserInputDevices =新的UserInputDevice [] {
新的XBoxOneController(),
新的PS3Controller(),
新的DualShock4Controller(),
新的KeyboardController()
}; 重写受保护的void Awake()
{base.Awake();
SetupCurrentUserInputDevice();
}私人无效SetupCurrentUserInputDevice()
{
currentUserInputDevice = System.Array.Find(supportedUserInputDevices,m => m.IsConnected());
} void Update()
{
currentUserInputDevice.PollButtons();
}}

PollButtons ,每个UserInputDevice广播处于按下状态的任何按钮的事件:

 公共无效PollButtons() 
{
ArrayList按钮= new ArrayList();
button.Add(JumpButton);
button.Add(ConfirmButton);
button.Add(PauseButton);
button.Add(DPad.LeftButton);
button.Add(DPad.RightButton);
button.Add(DPad.TopButton);
button.Add(DPad.BottomButton);
foreach(按钮中的按钮按钮)
{
如果(button.CurrentState == Button.State.Pressed)
{
OnButtonPress(按钮);
}
}
}

订户可以侦听此事件,并相应地执行逻辑。 例如,我有一个PlayerMovementController ,它根据来自当前连接的设备的传入事件来移动我的Player游戏对象:

 公共无效HandleButtonPress(按钮按钮) 
{
开关(button.action)
{
案例UserInputDevice.ButtonName.DPadLeft:
向左移动();
打破;
大小写UserInputDevice.ButtonName.DPadRight:
向右移();
打破;
案例UserInputDevice.ButtonName.DPadUp:
跳();
打破;
默认:
打破;
}
}

这种方法是很朴素的。 它很有意义并且目前感觉很好,但是我很好奇它在这个项目中是否具有持久力。

您如何处理项目中的用户输入? 我很乐意听到愿意分享想法的任何人的替代方法。

喜欢这个职位吗? 您可能会喜欢 BentoBlox 也可以-在 App Store 上查看游戏