Posts 유니티 - 키보드 연속 입력 유지 상태 감지하기
Post
Cancel

유니티 - 키보드 연속 입력 유지 상태 감지하기

활용


  • 달리기 구현(WW, AA, SS, DD)

Source Code


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
/// <summary> 키보드 연속 입력 유지 상태 감지 </summary>
private class DoubleKeyPressDetection
{
    public KeyCode Key { get; private set; }

    /// <summary> 한 번 눌러서 유지한 상태 </summary>
    public bool SinglePressed { get; private set; }

    /// <summary> 두 번 눌러서 유지한 상태 </summary>
    public bool DoublePressed { get; private set; }

    private bool  doublePressDetected;
    private float doublePressThreshold;
    private float lastKeyDownTime;

    public DoubleKeyPressDetection(KeyCode key, float threshold = 0.3f)
    {
        this.Key = key;
        SinglePressed = false;
        DoublePressed = false;
        doublePressDetected = false;
        doublePressThreshold = threshold;
        lastKeyDownTime = 0f;
    }

    public void ChangeKey(KeyCode key)
    {
        this.Key = key;
    }
    public void ChangeThreshold(float seconds)
    {
        doublePressThreshold = seconds > 0f ? seconds : 0f;
    }

    /// <summary> MonoBehaviour.Update()에서 호출 : 키 정보 업데이트 </summary>
    public void Update()
    {
        if (Input.GetKeyDown(Key))
        {
            doublePressDetected =
                (Time.time - lastKeyDownTime < doublePressThreshold);

            lastKeyDownTime = Time.time;
        }

        if (Input.GetKey(Key))
        {
            if (doublePressDetected)
                DoublePressed = true;
            else
                SinglePressed = true;
        }
        else
        {
            doublePressDetected = false;
            DoublePressed = false;
            SinglePressed = false;
        }
    }

    /// <summary> MonoBehaviour.Update()에서 호출 : 키 입력에 따른 동작 </summary>
    public void UpdateAction(Action singlePressAction, Action doublePressAction)
    {
        if(SinglePressed) singlePressAction?.Invoke();
        if(DoublePressed) doublePressAction?.Invoke();
    }
}

private DoubleKeyPressDetection[] keys;

private void Start()
{
    keys = new[]
    {
        new DoubleKeyPressDetection(KeyCode.W),
        new DoubleKeyPressDetection(KeyCode.A),
        new DoubleKeyPressDetection(KeyCode.S),
        new DoubleKeyPressDetection(KeyCode.D),
    };
}

private void Update()
{
    for (int i = 0; i < keys.Length; i++)
    {
        keys[i].Update();
    }

    keys[0].UpdateAction(() => Debug.Log("W"), () => Debug.Log("WW"));
    keys[1].UpdateAction(() => Debug.Log("A"), () => Debug.Log("AA"));
    keys[2].UpdateAction(() => Debug.Log("S"), () => Debug.Log("SS"));
    keys[3].UpdateAction(() => Debug.Log("D"), () => Debug.Log("DD"));
}
This post is licensed under CC BY 4.0 by the author.