常用的Unity輸入方法

zlllIII發表於2024-09-12

以下是一些常用的Unity輸入方法的總結。

1. Input.GetKeyDown(KeyCode key)

返回值:bool。如果使用者在上一幀沒有按下指定的鍵,但在當前幀按下了,則返回true;否則返回false。

例子:

if (Input.GetKeyDown(KeyCode.Space))  
{  
    Debug.Log("空格鍵被按下!");  
}

2. Input.GetKey(KeyCode key)

返回值:bool。如果使用者在當前幀按下了指定的鍵,則返回true;否則返回false。
例子:

if (Input.GetKey(KeyCode.W))  
{  
    // 向前移動  
}

3. Input.GetKeyUp(KeyCode key)

返回值:bool。如果使用者在上一幀按下了指定的鍵,但在當前幀釋放了,則返回true;否則返回false。

例子:

if (Input.GetKeyUp(KeyCode.Escape))  
{  
    // 退出遊戲  
}

4. Input.GetAxis("Horizontal") 和 Input.GetAxis("Vertical")

返回值:float。對於“Horizontal”軸,正值表示向右,負值表示向左;對於“Vertical”軸,正值表示向上,負值表示向下。如果沒有輸入,則返回0。滾輪上滑為正,下滑為負;且滾輪的每個小格卡頓,其數值資訊表示為0.1,快速連續滾動時其數值會直接出現對應的數值,不會一格一格出現。

可以使用Input.GetAxis("Mouse X")獲取滑鼠在水平方向上的移動量,使用Input.GetAxis("Mouse Y")獲取滑鼠在垂直方向上的移動量。

例子:

float moveX = Input.GetAxis("Horizontal") * Time.deltaTime;  
float moveY = Input.GetAxis("Vertical") * Time.deltaTime;  
float scroll = Input.GetAxis("Mouse ScrollWheel");  //滾輪
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");

5. Input.GetMouseButton(int button)

返回值:bool。如果當前幀使用者按下了指定的滑鼠按鈕(0代表左鍵,1代表右鍵,2代表中鍵),則返回true;否則返回false。

例子:

if (Input.GetMouseButton(0))  
{  
    // 滑鼠左鍵被按下  
}

6. Input.GetMouseButtonDown(int button)

返回值:bool。如果使用者在上一幀沒有按下指定的滑鼠按鈕,但在當前幀按下了,則返回true;否則返回false。

例子:

if (Input.GetMouseButtonDown(0))  
{  
    // 滑鼠左鍵被按下  
}

7. Input.GetMouseButtonUp(int button)

返回值:bool。如果使用者在上一幀按下了指定的滑鼠按鈕,但在當前幀釋放了,則返回true;否則返回false。

例子:

if (Input.GetMouseButtonUp(0))  
{  
    // 滑鼠左鍵被釋放  
}

8. Input.mousePosition

返回值:Vector3。表示滑鼠在螢幕上的位置(以畫素為單位),左下角為(0,0),右上角為(Screen.width, Screen.height)。

例子:

Vector3 mousePos = Input.mousePosition;  
// 可以將滑鼠位置轉換為世界空間中的位置  
RaycastHit hit;  
if (Physics.Raycast(Camera.main.ScreenPointToRay(mousePos), out hit))  
{  
    // 射線擊中了物體  
}

相關文章