1. 程式人生 > >Unity的Input輸入

Unity的Input輸入

children bject tutorials unity 空格 tco lin 中文翻譯 manager

Unity中的輸入管理器由Input類進行操控。官方文檔地址:https://docs.unity3d.com/ScriptReference/Input.html

中文翻譯的話可以在這裏:http://www.ceeger.com/Script/Input/Input.html

這裏只說幾個易混淆的點。

既然已經有GetKey、GetKeyDown、GetKeyUp 以及 GetMouseButton、GetMouseButtonDown、GetMouseButtonUp,為什麽還要有GetButton、GetButtonDown、GetButtonUp呢?

Down、Up分別表示按下、松開,Key、Mouse很容易理解:分別表示鍵盤、鼠標,GetKey、GetMouse表示按下後沒有釋放這個動作,類似 Press。

我們知道鍵盤的按鍵位置是固定的,鼠標左、右、中鍵也是固定的,也就是映射關系是固定的。而Button是輸入管理器 InputManager所定義的虛擬器,它通過名稱來訪問。怎麽理解,先看下圖。

Input 的設置可以通過 Edit –> Project Settings –> Input打開面板

技術分享

如果我需要判斷是否進行了跳躍(Jump),可以在代碼中這樣寫。

if (Input.GetButtonDown("Jump"))
{
    Debug.Log("Input Button Down Jump.");
}

運行,當按下空格鍵,控制臺就會輸出“Input Button Down Jump.”。而如果把Positive Button 修改一下,不是 space 也是 k,此時當你按下鍵盤上的 k 時,控制臺才會有輸出,而按空格鍵則是沒有反應的。它通過名稱來進行映射,相較前面 的key、mouse會靈活一些。

鼠標事件的左、中、右鍵,分別對應的值是0、2、1。

if(Input.GetMouseButton(0)) {
    //左鍵被按下, 放在 Update 方法中會被不斷觸發

}

if(Input.GetMouseButtonDown(1)) {
    //右鍵按下

}

if(Input.GetMouseButtonUp(2)) {
    //中鍵擡起
    
}

鍵盤對應的字符通過KeyCode可以直接獲得,下面的代碼當按下鍵盤A鍵時在當前節點下添加一個“Button”對應,當按下 D 鍵時刪除一個節點。

if (Input.GetKeyDown(KeyCode.A))
{
    Button newButton 
= Instantiate(button); newButton.transform.SetParent(this.gameObject.transform, false); } else if (Input.GetKeyDown(KeyCode.D)) { Button[] buttonChilds = gameObject.GetComponentsInChildren<Button>(); List<Button> buttonList = new List<Button>(buttonChilds); int nCount = buttonList.Count; if (nCount > 1) { Button tmpButton = buttonList[nCount - 1]; Destroy(tmpButton.gameObject); } }

利用 GetAxis 可以制作搖桿(鍵盤的 上、下、左、右,以及 A、W、S、D),來對遊戲對象進行移動(Translate)、旋轉(Rotate)。返回值的範圍是[-1, 1],可以自行設定間隔大小,比如每次只增、減0.01,詳情可查看官網的視頻:https://unity3d.com/cn/learn/tutorials/topics/scripting/getaxis

Unity的Input輸入