如何轮询控制器输入在UWP应用程序 [英] How to Poll For Controller Input In UWP App
问题描述
我不确定如何获取和更新从使用UWP中的GamePad类监控的控制器接收的输入的最佳实践。
I'm unsure about the best practice for obtaining and updating input received from a controller monitored using the GamePad class in UWP.
我看过几个在GamePadAdded事件中使用Dispatch Timers和异步循环的人的示例。在Win32应用程序中,我将在WinMain更新/消息循环中处理输入,但是在UWP应用程序中,我不知道有什么相似之处。
I've seen a couple of examples of people using Dispatch Timers and async loops inside the GamePadAdded event. In Win32 applications, I would have handled input in the WinMain update/message loop, but in UWP apps I don't know of anything similar.
输入的UWP应用程序应该像Win32应用程序一样收集/处理?
Is there a loop in UWP apps that input should be collected/handled like in Win32 apps? What is the recommended protocol for polling for input from a input device (nominally a Xbox One controller)?
我很高兴了解更多有关UWP应用程序开发的信息,
I'm happy to read more about UWP app development but I'm unsure of any guides that reference something like this.
编辑:这将是有成效的,如果,而不是downvoting和移动,你分享了为什么这个问题应该得到downvote。
It would be productive if, instead of downvoting and moving on, you shared thoughts on why this question deserved a downvote.
推荐答案
我看过几个使用调度计时器和异步循环在GamePadAdded事件内
I've seen a couple of examples of people using Dispatch Timers and async loops inside the GamePadAdded event
这是UWP应用程序读取Gamepad数据的正确方法。有一点建议是,如果你需要更新UI频繁,移动UI线程上的循环读部分。请参阅此 blog
This is the right way in UWP app to read Gamepad data. A little suggestion is, move the loop reading part on UI thread if you need to update UI frequently. See the solution in this blog
在UWP应用程序中有一个循环,输入应该像Win32应用程序一样被收集/处理
Is there a loop in UWP apps that input should be collected/handled like in Win32 apps
您可以使用自定义事件创建一个包装器,请参阅开源实现: XBoxGamepad
You may make a wrapper with custom event, see the open source implementation: XBoxGamepad
public class XBoxGamepad
{
private List<Gamepad> _controllers = new List<Gamepad>();
private bool _running = true;
Task backgroundWorkTask;
public event EventHandler<GamepadButtons> OnXBoxGamepadButtonPressA;
//omitted......
public XBoxGamepad()
{
Gamepad.GamepadAdded += Gamepad_GamepadAdded;
Gamepad.GamepadRemoved += Gamepad_GamepadRemoved;
backgroundWorkTask = Task.Run(() => PollGamepad());
}
//omitted......
private void Start()
{
_running = true;
}
public void Stop()
{
_running = false;
}
public async Task PollGamepad()
{
while (true)
{
if (_running)
{
foreach (Gamepad controller in _controllers)
{
if (controller.GetCurrentReading().Buttons == GamepadButtons.A)
{
OnXBoxGamepadButtonPressA(controller, controller.GetCurrentReading().Buttons);
}
//omitted......
}
}
await Task.Delay(50);
}
}
private void Gamepad_GamepadRemoved(object sender, Gamepad e)
{
_controllers.Remove(e);
}
private void Gamepad_GamepadAdded(object sender, Gamepad e)
{
_controllers.Add(e);
}
}
这篇关于如何轮询控制器输入在UWP应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!