XBox Controller Input in .NET in 60 seconds

xboxcontroller

The folks developing SharpDX do a fantastic job of a .NET Managed DirectX layer. I’m an impatient person, and I think XBox Controllers are awesome input devices. So, here’s a library available as a NuGet package that builds upon SharpDX and boils it down to super-simple code; scientific studies have shown that the average developer can now use an XBox Controller in under 60 seconds.

Like, if you wanted to find out if Button A was pressed on the first connected controller:

var myController = BrandonPotter.XBox.XBoxController.GetConnectedControllers().FirstOrDefault();
if (myController.ButtonAPressed)
{
// do something if button A is pressed
}

Now that I teased you, go get it off NuGet here:

https://www.nuget.org/packages/XBoxController

… or go fork it and improve it here:

https://github.com/BrandonPotter/XBoxController

But wait, there’s more. XBox controllers are tricky. This little library addresses the following common issues when dealing with them…

Percentages instead of raw values – In reality, the thumb pads have values between –32,767 to +32,768. The triggers have values of 0 to 65,000. For all practical purposes, these are pretty meaningless, so these types of ranges are converted to percentages (as a double with crazy precisions). When each thumb pad is at its center position, this is 50% X / 50% Y. So from here on out, we’re going to be talking percentages, mmkay?

Trigger On/Off – Left and right triggers (the little, well, triggers that resemble the trigger of a gun) on the front of the controller) are, in reality, never actually “on” or “off”, they’re in between 0-100%. However, you may notice that the XBoxController class has two boolean properties called TriggerLeftPressed andTriggerRightPressed. These are inferred based on the current trigger percentage value, and two more properties (TriggerLeftPressThreshold / TriggerRightPressThreshold), which define the minimum percentage values the trigger needs to meet in order to be considered pressed. Defaults to 10%, as I found this was a pretty comfortable place to consider it “pressed”.

Dead Zone – The thumb pads do have springs to snap them back to “center”. However, with 65,535 positions on each axis, rarely will “center” ever mean the same thing twice. If you’re counting on 50/50 being “no thumb on the thumbpad”, this will drive you insane. So, I needed some kind of a ‘dead zone’ to go ahead and assume 50/50 when it’s in the “close enough to be considered the center” area. Through sheer trial and error I determined that a reliable center is anywhere from a 40% to 60% position. If you want this to be more or less sensitive, just set theSnapDeadZoneTolerance property. The tolerance is the percentage value that we consider to be in the “dead zone” on either side of 50%. So, for a Dead Zone Tolerance of 10, this means “10% on either side of 50%”, so 40% – 60%. A tolerance of 5 would mean the dead zone is between 55% – 65%, and of course a tolerance of 0 would disable the assumed dead zone.

Controller Polling / Refresh – To get new controller state information, we have to poll the XBox Controller. This little library will handle it automatically, so you can just grab properties and go. By default, this will poll the device a maximum of every 30 milliseconds. This felt comfortable to me, but if you need faster or slower polling, just adjust the RefreshIntervalMilliseconds property.

Controller Connect/Disconnect – At some point, your user will disconnect the controller while your application is using it; nothing should crash, and the controller’s IsConnected property should return false once it’s disconnected with no blow ups. Reconnection happens automagically.

Vibration Motors – The XBox Controller has 2 vibration motors, a left and right. The left motor (let’s call it “the big vibrations”), when set to 100%, will send your XBox controller walking across whatever surface it’s on. The right motor resembles what’s in your cell phone. You can set the motors (again, with percentages here) by calling SetLeftMotorVibrationSpeed() and SetRightMotorVibrationSpeed().

That’s about it. If you use this library and there’s anything I have forgotten, I’d love to hear. Happy coding!

  • Zerq The Mad

    Hmmmm... i get the following on GetConnectedControllers not sure what wrong...
    i did try using DXsharpInput to get the raw data and that works fine so i dont see why i should get this error....

    System.DllNotFoundException was unhandled
    HResult=-2146233052
    Message=Unable to load DLL 'xinput1_3.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
    Source=SharpDX.XInput
    TypeName=""
    StackTrace:
    at SharpDX.XInput.XInput.XInputGetState_(Int32 arg0, Void* arg1)
    at SharpDX.XInput.XInput.XInputGetState(Int32 dwUserIndex, State& stateRef)
    at SharpDX.XInput.Controller.GetState()
    at BrandonPotter.XBox.XBoxController.RefreshControllerState()
    at BrandonPotter.XBox.XBoxController.EnsureRefresh()
    at BrandonPotter.XBox.XBoxController.get_IsConnected()
    at BrandonPotter.XBox.XBoxController.b__0(XBoxController c)
    at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
    at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
    at BrandonPotter.XBox.XBoxController.GetConnectedControllers()
    at GamePadTest.Program.Main(String[] args) in C:UsersUserSourceReposZerqVariousConsoleApplication1GamePadTestProgram.cs:line 11
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
    InnerException: