1. 程式人生 > >雙擊事件的檢測(基於C#和Unity)

雙擊事件的檢測(基於C#和Unity)

但是它是檢測滑鼠雙擊事件的,我們需要進行鍵盤上的單擊和雙擊。所以在他的基礎上進行進一步修改:

private bool keyDownStatus;
private int keyDownCount;
private float lastTime;
private float currentTime;

//key -> 要監聽的按鍵, timeElapse -> 雙擊之間最大時間間隔
bool DoubleClick(KeyCode key, float timeElapse) {
        //down --> mouseDownStatus = true; //up --> mouseDownStatus = false
if (Input.GetKeyDown(key)) { if (!keyDownStatus) { keyDownStatus = true; //Debug.Log("clicked"); if (keyDownCount == 0) {// 如果按住數量為 0 lastTime = Time.realtimeSinceStartup;// 記錄最後時間 } keyDownCount++; } } if
(Input.GetKeyUp(key)) { keyDownStatus = false; } if (keyDownStatus) { if (keyDownCount >= 2) { currentTime = Time.realtimeSinceStartup; if (currentTime - lastTime < timeElapse) { lastTime = currentTime; keyDownCount = 0
; //Debug.Log("Double clicked"); return true;//返回結果,確認雙擊 } else { lastTime = Time.realtimeSinceStartup; // 記錄最後時間 keyDownCount = 1; } } } return false; }