1. 程式人生 > >Unity之路(二):輸入事件管理Input

Unity之路(二):輸入事件管理Input

在Unity中輸入時間有Input類來管理輸入事件,常用方法:

// 鍵盤事件
public static bool GetKeyDwon(enum KeyCode); // 按鍵按下(觸發一次)
public static bool GetKeyDwon(enum KeyCode); // 按鍵放開(觸發一次)
public static bool GetKey(enum KeyCode); // 持續按下(持續觸發)

// 滑鼠事件 button:0-左鍵,1-右鍵,2-中介軟體
public static bool GetMouseButtonDown(int button); // 滑鼠按下(觸發一次)
public
static bool GetMouseButtonUp(int button); // 滑鼠放開(觸發一次) public static bool GetMouseButton(int button); // 滑鼠按下(持續觸發) // 觸控時間 public static int touchCount { get; }; // 觸控點個數 public static Touch GetTouch(int index); // 觸控事件

TouchPhase

Values Description
Began A finger touched the screen
Moved A finger moved on the screen
Stationary A finger is touching the screen but hasn’t moved
Ended A finger was lifted from the screen. This is the final phase of a touch
Canceled The system cancelled tracking for the touch, as when (for example) the user puts the device to her face or more than five touches happened simultaneously. This is the final phase of a touch

輸入事件需要在Update方法中處理。

示例:

void Update() 
{
    if (Input.GetKey(KeyCode.D)) {
        print('button d');
    }

    if (Input.GetMouseButton(0)) {
        print('left');
    }

     while (i < Input.touchCount) {  
        if (Input.GetTouch(i).phase == TouchPhase.Began) {  
            print(i + 'began');
        }  
}

print 只能在執行時類(MonoBehaviour的子類)中使用;
其他地方使用Debug.Log列印。