Using Gamepad API in Uno Platform apps

Uno Platform WinUI

2 years ago

Back in the Windows Phone days I have released a small game called Alchemy 10 on the Microsoft Store. I'm now working on bringing this game to all platforms and devices using Uno Platform. Because it uses the same XAML and C# as Windows App SDK, the process of porting is a breeze. But to make things even more interesting, I decided to add some new capabilities to the game. One of them is Gamepad support ? . However, to have it working everywhere, adding the Windows.Gaming.Input.Gamepad API to Uno Platform was needed. I worked on this API through several live coding sessions on Twitch and YouTube (see here) and last week it was finally merged (PR here) into the latest preview version of Uno Platform! In this article I would like to show you how to use gamepads in your Uno Platform applications running on Windows, iOS, macOS, Android and even the web using WebAssembly!

Uno Platform + Gamepad API

Prerequisites

To light up the Gamepad capabilities in Uno Platform app you need to update to Uno Platform 4.3.dev-205 or newer. If you are using the NuGet Package Manager in Visual Studio, make sure to check the "Include Prerelease" checkbox to find the preview version.

Enumerating gamepads and listening to connections

The GamepadAdded and GamepadRemoved events can be used to receive notifications on when individual gamepads are connected and disconnected. To list all currently connected game controllers, you can use the Gamepad.Gamepads property:

The Gamepads property gives you a list of Gamepad instances, each representing one of the gamepads.

Retrieving gamepad readings

With an instance of Gamepad you can start retrieving its readings by calling the GetCurrentReading() method:

For the thumbsticks X and Y properties are double values in the range from -1 to 1, and for triggers the values range from 0 to 1. The Buttons property is an flags enum which gives you all the currenty pressed buttons on the gamepad. You can check whether a specific button is pressed by using HasFlag method:

Source code

To see the code in this article in action, you can browse it on my GitHub. You can also clone it and deploy on any of your desktop or mobile devices.

Live demo

If you just want to try it out, you can open my sample application at cutt.ly/apis and browse the Gamepad section in the navigation menu. You can even run this in your mobile browser - just connect up your gamepads to your Android or iOS device and they will show up in the list! Even this application is open-source and you can find it here, if you want to deploy it to any of your mobile devices.

Summary

This is the very first release of Gamepad API support in Uno Platform, so there is definitely room for improvements including adding support for historical readings and improving reading performance. If you have any feedback or want to contribute, please see Uno Platform on GitHub!