1. 程式人生 > >U3D Input類之鍵位輸入GetKey

U3D Input類之鍵位輸入GetKey

tle cti 3.2 sta 詳細 row u3d engine 內容

  Input類中包含許多屬性和方法,下面介紹一下和鍵盤輸入有關的內容

一、有關接收鍵盤信息的屬性

屬性名 類型 屬性類型 含義
anyKey bool get 當前是否按住任意鍵或鼠標按鈕
anyKeyDown bool get 是否按下任意鍵
using UnityEngine;

public class Example : MonoBehaviour
{
    // Detects if any key has been pressed.

    void Update()
    {
        if (Input.anyKey)
        {
            Debug.Log(
"A key or mouse click has been detected"); } } }

using UnityEngine;

public class Example : MonoBehaviour
{
    // Detects if any key has been pressed down.

    void Update()
    {
        if (Input.anyKeyDown)
        {
            Debug.Log("A key or mouse click has been detected");
        }
    }
}

註:對於anyKeyDown,您應該從Update函數中輪詢此變量,因為每個幀都會重置狀態。在用戶釋放所有鍵/按鈕並再次按下任何鍵/按鈕之前,它不會返回true。

二、鍵盤按鍵的keyCode鍵碼

  在網上看到別人關於鍵碼的內容非常詳細,這裏就直接上鏈接了

  點擊查看:keyCode鍵碼大全

三、有關接收鍵盤信息的方法

  3.1 public static bool GetKey(KeyCode key)  

參數:key———鍵盤上的某個鍵。

返回值:bool———當通過名稱指定的按鍵被用戶按住時返回true

using UnityEngine;
using System.Collections; public class ExampleClass : MonoBehaviour { void Update() { if (Input.GetKey(KeyCode.UpArrow)) { print("up arrow key is held down"); } if (Input.GetKey(KeyCode.DownArrow)) { print("down arrow key is held down"); } } }

  它還有一個重載方法: public static bool GetKey(string name),它的參數為字符串

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey("up"))
        {
            print("up arrow key is held down");
        }

        if (Input.GetKey("down"))
        {
            print("down arrow key is held down");
        }
    }
}

  3.2 public static bool GetKeyDown(KeyCode key)

    當用戶按下指定名稱的按鍵期間的幀返回true。

    您需要從Update函數調用此函數,因為每個幀都會重置狀態。在用戶釋放該鍵並再次按下該鍵之前,它不會返回true。

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            print("space key was pressed");
        }
    }
}

    重載方法:public static bool GetKeyDown(string name)

  3.3 public static bool GetKeyUp(KeyCode key)

    在用戶釋放給定名字的按鍵的那一幀返回true。

    您需要從Update函數調用此函數,因為每個幀都會重置狀態。在用戶按下鍵並再次釋放它之前,它不會返回true。

using UnityEngine;

public class Example : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
        {
            print("space key was released");
        }
    }
}

  重載方法:public static bool GetKeyUp(string name)

  下面例子演示了如何使物體隨著按鍵的方向移動

void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
            dir = Vector2.right;
        else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
            dir = Vector2.left;
        else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
            dir = Vector2.down;
        else if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
            dir = Vector2.up;
    }

U3D Input類之鍵位輸入GetKey