KeyboardInput单例模式

upload successful

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
using UnityEngine;

namespace Client.Input
{
public class KeyboardInput : MonoBehaviour
{
private static KeyboardInput _instance;

public static KeyboardInput Instance
{
get
{
if (_instance) return _instance;
_instance = FindObjectOfType<KeyboardInput>();
if (_instance) return _instance;
var go = new GameObject("KeyboardInput");
_instance = go.AddComponent<KeyboardInput>();

return _instance;
}
}

public Vector2 Direction { get; private set; }

private void Awake()
{
if (_instance is not null && _instance != this)
{
Destroy(gameObject);
}
else
{
_instance = this;
}
}

private void Update()
{
if (UnityEngine.Input.GetKey(KeyCode.A))
{
Direction = new Vector2(-1, Direction.y);
}

if (UnityEngine.Input.GetKey(KeyCode.D))
{
Direction = new Vector2(1, Direction.y);
}

if (UnityEngine.Input.GetKey(KeyCode.W))
{
Direction = new Vector2(Direction.x, 1);
}

if (UnityEngine.Input.GetKey(KeyCode.S))
{
Direction = new Vector2(Direction.x, -1);
}

if (UnityEngine.Input.GetKey(KeyCode.A) && UnityEngine.Input.GetKey(KeyCode.D))
{
Direction = new Vector2(0, Direction.y);
}

if (!UnityEngine.Input.GetKey(KeyCode.A) && !UnityEngine.Input.GetKey(KeyCode.D))
{
Direction = new Vector2(0, Direction.y);
}

if (UnityEngine.Input.GetKey(KeyCode.W) && UnityEngine.Input.GetKey(KeyCode.S))
{
Direction = new Vector2(Direction.x, 0);
}

if (!UnityEngine.Input.GetKey(KeyCode.W) && !UnityEngine.Input.GetKey(KeyCode.S))
{
Direction = new Vector2(Direction.x, 0);
}

}
}
}

GetKey可能并不完美,但是在后期供玩家修改键位时会有用。但也不推荐,现在我们可以使用Unity新的输入系统,这里不做过多介绍。