GetGamepad no longer throws if slot is empty

main
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 TriggerRight { get; } = new Trigger();
public bool IsDummy => Handle == IntPtr.Zero;
private Dictionary<SDL.SDL_GameControllerButton, Button> EnumToButton;
private Dictionary<SDL.SDL_GameControllerAxis, Axis> EnumToAxis;
private Dictionary<SDL.SDL_GameControllerAxis, Trigger> EnumToTrigger;
@ -77,23 +79,26 @@ namespace MoonWorks.Input
internal void Update()
{
foreach (var (sdlEnum, button) in EnumToButton)
if (!IsDummy)
{
button.Update(CheckPressed(sdlEnum));
}
foreach (var (sdlEnum, button) in EnumToButton)
{
button.Update(CheckPressed(sdlEnum));
}
foreach (var (sdlEnum, axis) in EnumToAxis)
{
var sdlAxisValue = SDL.SDL_GameControllerGetAxis(Handle, sdlEnum);
var axisValue = Normalize(sdlAxisValue, short.MinValue, short.MaxValue, -1, 1);
axis.Update(axisValue);
}
foreach (var (sdlEnum, axis) in EnumToAxis)
{
var sdlAxisValue = SDL.SDL_GameControllerGetAxis(Handle, sdlEnum);
var axisValue = Normalize(sdlAxisValue, short.MinValue, short.MaxValue, -1, 1);
axis.Update(axisValue);
}
foreach (var (sdlEnum, trigger) in EnumToTrigger)
{
var sdlAxisValue = SDL.SDL_GameControllerGetAxis(Handle, sdlEnum);
var axisValue = Normalize(sdlAxisValue, 0, short.MaxValue, 0, 1);
trigger.Update(axisValue);
foreach (var (sdlEnum, trigger) in EnumToTrigger)
{
var sdlAxisValue = SDL.SDL_GameControllerGetAxis(Handle, sdlEnum);
var axisValue = Normalize(sdlAxisValue, 0, short.MaxValue, 0, 1);
trigger.Update(axisValue);
}
}
}

View File

@ -1,15 +1,16 @@
using SDL2;
using System;
using System.Collections.Generic;
namespace MoonWorks.Input
{
public class Inputs
{
public const int MAX_GAMEPADS = 4;
public Keyboard Keyboard { get; }
public Mouse Mouse { get; }
List<Gamepad> gamepads = new List<Gamepad>();
Gamepad[] gamepads;
public static event Action<char> TextInput;
@ -18,11 +19,17 @@ namespace MoonWorks.Input
Keyboard = new Keyboard();
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)
{
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)
{
return slot < gamepads.Count;
return !gamepads[slot].IsDummy;
}
public Gamepad GetGamepad(int slot)