A simple .NET Framework to make 2D games quick and easy.
at main 91 lines 2.6 kB view raw
1using System.Reflection; 2using Fjord.Scenes; 3 4namespace Fjord.Input; 5 6public record InputEvent { 7 public record Keyboard(Key key, params Mod[] mods) : InputEvent(); 8 public record Mouse(MB mb, params Mod[] mods) : InputEvent(); 9} 10 11public interface InputAction 12{ 13 public InputEvent[] Events { get; init; } 14} 15 16public static class GlobalInput 17{ 18 private static List<InputAction> _actions = new(); 19 20 public static void Initialize() 21 { 22 Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 23 foreach(var assembly in assemblies) { 24 var derivedTypes = assembly.GetTypes().Where(t => 25 t != typeof(InputAction) && 26 typeof(InputAction).IsAssignableFrom(t)); 27 28 foreach (var type in derivedTypes) 29 { 30 var action = Activator.CreateInstance(type) as InputAction; 31 _register(action!); 32 } 33 } 34 } 35 36 public static bool Pressed<T>() where T : InputAction 37 { 38 for (var i = 0; i < _actions.Count; i++) 39 { 40 if(_actions[i].GetType() != typeof(T)) 41 continue; 42 43 return _actions[i].Events.Any(e => e switch { 44 InputEvent.Keyboard ev => GlobalKeyboard.Pressed(ev.key, ev.mods), 45 InputEvent.Mouse ev => GlobalMouse.Pressed(ev.mb, ev.mods), 46 _ => false 47 }); 48 } 49 50 return false; 51 } 52 53 public static bool Released<T>() where T : InputAction 54 { 55 for (var i = 0; i < _actions.Count; i++) 56 { 57 if(_actions[i].GetType() != typeof(T)) 58 continue; 59 60 return _actions[i].Events.Any(e => e switch { 61 InputEvent.Keyboard ev => GlobalKeyboard.Released(ev.key, ev.mods), 62 InputEvent.Mouse ev => GlobalMouse.Released(ev.mb, ev.mods), 63 _ => false 64 }); 65 } 66 67 return false; 68 } 69 70 public static bool Down<T>() where T : InputAction 71 { 72 for (var i = 0; i < _actions.Count; i++) 73 { 74 if(_actions[i].GetType() != typeof(T)) 75 continue; 76 77 return _actions[i].Events.Any(e => e switch { 78 InputEvent.Keyboard ev => GlobalKeyboard.Down(ev.key, ev.mods), 79 InputEvent.Mouse ev => GlobalMouse.Down(ev.mb, ev.mods), 80 _ => false 81 }); 82 } 83 84 return false; 85 } 86 87 private static void _register(InputAction action) 88 { 89 _actions.Add(action); 90 } 91}