Unit3D--人機交互入門

人機交互主要是指玩家通過使用鍵盤和鼠標來控制和操作遊戲內容,而Unity3D中人機交互的實現,在腳本層就是通過觸及事件來響應的。

鍵盤輸入

  1. input.GetKey 獲取鍵
    當用戶按下由name名稱確定的按鍵時,然後true。想想自動開火。
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");

    }
}
  1. Input.GetKeyDown 獲取鍵按下
    當用戶按下指定名稱的按鍵時的那一幀返回true。
  2. Input.GetKeyUp 獲取鍵彈起
    在用戶釋放給定名字的按鍵的那一幀返回true。

例如簡單檢驗一串特定密碼

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {
    string key = "";
    void Update () {
        if (Input.GetKeyDown(KeyCode.A)) key += "A";
        else if (Input.GetKeyDown(KeyCode.B)) key += "B";
        else if (Input.GetKeyDown(KeyCode.C)) key += "C";
        if (key == "ABC")
        {
            key = "";
            print("Right key you are press!");
        }
    }
}

鼠標輸入

  1. Input.GetMouseButton 獲取鼠標按鈕
    當指定的鼠標按鈕被按下時返回true。其中,button值設定爲 0對應左鍵 , 1對應右鍵 , 2對應中鍵。
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        if (Input.GetMouseButton(0))
            Debug.Log("Pressed left click.");

        if (Input.GetMouseButton(1))
            Debug.Log("Pressed right click.");

        if (Input.GetMouseButton(2))
            Debug.Log("Pressed middle click.");

    }
}

2.Input.GetMouseButtonDown 獲取鼠標按鈕按下
在用戶按下指定鼠標按鍵的那一幀返回true。
3. Input.GetMouseButtonDown 獲取鼠標按鈕按下
在用戶釋放指定鼠標按鍵的那一幀返回true。

例如檢驗鼠標雙擊效果:

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {
    public int Clickcount = 0;

    void Update () {
        if (Input.GetMouseButtonDown(0))
            Clickcount++;

        if (Clickcount == 2) {
            Clickcount = 0;
            Debug.Log("Double clicked\n");
        }
    }
}
發佈了37 篇原創文章 · 獲贊 121 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章