GetGamepad no longer throws if slot is empty

pull/17/head
cosmonaut 2022-03-18 12:11:00 -07:00
parent 71d9f8f4fe
commit cc876b2132
2 changed files with 31 additions and 19 deletions

View File

@ -33,6 +33,8 @@ namespace MoonWorks.Input
public Trigger TriggerLeft { get; } = new Trigger(); public Trigger TriggerLeft { get; } = new Trigger();
public Trigger TriggerRight { get; } = new Trigger(); public Trigger TriggerRight { get; } = new Trigger();
public bool IsDummy => Handle == IntPtr.Zero;
private Dictionary<SDL.SDL_GameControllerButton, Button> EnumToButton; private Dictionary<SDL.SDL_GameControllerButton, Button> EnumToButton;
private Dictionary<SDL.SDL_GameControllerAxis, Axis> EnumToAxis; private Dictionary<SDL.SDL_GameControllerAxis, Axis> EnumToAxis;
private Dictionary<SDL.SDL_GameControllerAxis, Trigger> EnumToTrigger; private Dictionary<SDL.SDL_GameControllerAxis, Trigger> EnumToTrigger;
@ -76,6 +78,8 @@ namespace MoonWorks.Input
} }
internal void Update() internal void Update()
{
if (!IsDummy)
{ {
foreach (var (sdlEnum, button) in EnumToButton) foreach (var (sdlEnum, button) in EnumToButton)
{ {
@ -96,6 +100,7 @@ namespace MoonWorks.Input
trigger.Update(axisValue); trigger.Update(axisValue);
} }
} }
}
/// <summary> /// <summary>
/// Sets vibration values on the left and right motors. /// Sets vibration values on the left and right motors.

View File

@ -1,15 +1,16 @@
using SDL2; using SDL2;
using System; using System;
using System.Collections.Generic;
namespace MoonWorks.Input namespace MoonWorks.Input
{ {
public class Inputs public class Inputs
{ {
public const int MAX_GAMEPADS = 4;
public Keyboard Keyboard { get; } public Keyboard Keyboard { get; }
public Mouse Mouse { get; } public Mouse Mouse { get; }
List<Gamepad> gamepads = new List<Gamepad>(); Gamepad[] gamepads;
public static event Action<char> TextInput; public static event Action<char> TextInput;
@ -18,11 +19,17 @@ namespace MoonWorks.Input
Keyboard = new Keyboard(); Keyboard = new Keyboard();
Mouse = new Mouse(); Mouse = new Mouse();
for (int i = 0; i < SDL.SDL_NumJoysticks(); i++) gamepads = new Gamepad[MAX_GAMEPADS];
for (var i = 0; i < 4; i += 1)
{ {
if (SDL.SDL_IsGameController(i) == SDL.SDL_bool.SDL_TRUE) if (SDL.SDL_IsGameController(i) == SDL.SDL_bool.SDL_TRUE)
{ {
gamepads.Add(new Gamepad(SDL.SDL_GameControllerOpen(i))); gamepads[i] = new Gamepad(SDL.SDL_GameControllerOpen(i));
}
else
{
gamepads[i] = new Gamepad(IntPtr.Zero);
} }
} }
} }
@ -41,7 +48,7 @@ namespace MoonWorks.Input
public bool GamepadExists(int slot) public bool GamepadExists(int slot)
{ {
return slot < gamepads.Count; return !gamepads[slot].IsDummy;
} }
public Gamepad GetGamepad(int slot) public Gamepad GetGamepad(int slot)