-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputManager.cs
97 lines (80 loc) · 2 KB
/
InputManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace CrappyGame
{
public class InputManager
{
public delegate void InputActionDelegate(Key key, GameTime time);
private class InputActionHandler
{
public event InputActionDelegate KeyDown;
public event InputActionDelegate KeyPressed;
public event InputActionDelegate KeyUp;
public bool WasDown { get; set; }
public void FireKeyDown(Key key, GameTime time)
{
if(KeyDown != null)
KeyDown(key, time);
}
public void FireKeyPressed(Key key, GameTime time)
{
if(KeyPressed != null)
KeyPressed(key, time);
}
public void FireKeyUp(Key key, GameTime time)
{
if(KeyUp != null)
KeyUp(key, time);
}
}
Dictionary<Key, InputActionHandler> KeyHandlers { get; set; }
public InputManager()
{
KeyHandlers = new Dictionary<Key, InputActionHandler>();
}
public void ProcessInput(GameTime time)
{
foreach(var keyHandlerPair in KeyHandlers)
{
Key key = keyHandlerPair.Key;
InputActionHandler handler = keyHandlerPair.Value;
bool keyIsDown = Keyboard.IsKeyDown(key);
if(keyIsDown)
{
if(!handler.WasDown)
{
handler.WasDown = true;
KeyHandlers[key].FireKeyDown(key, time);
}
KeyHandlers[key].FireKeyPressed(key, time);
}
else if(handler.WasDown)
{
handler.WasDown = false;
KeyHandlers[key].FireKeyUp(key, time);
}
}
}
public void RegisterKeyDown(Key key, InputActionDelegate action)
{
GetInputAction(key).KeyDown += action; ;
}
public void RegisterKeyPressed(Key key, InputActionDelegate action)
{
GetInputAction(key).KeyPressed += action; ;
}
public void RegisterKeyUp(Key key, InputActionDelegate action)
{
GetInputAction(key).KeyUp += action;
}
private InputActionHandler GetInputAction(Key key)
{
if(!KeyHandlers.ContainsKey(key))
KeyHandlers[key] = new InputActionHandler();
return KeyHandlers[key];
}
}
}