鍵盤事件
按下事件:Input.GetKeyDown()
例如:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("您按下了“W”");
}
if (Input.GetKeyDown(KeyCode.S))
{
Debug.Log("您按下了“S”");
}
if (Input.GetKeyDown(KeyCode.D))
{
Debug.Log("您按下了“D”");
}
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("您按下了“A”");
}
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("您按下了“空格”");
}
}
}
擡起事件:Input.GetKeyUp() (用法和按下時間差不多,省略)
長按事件:Input.GetKey()
下面是一個檢測連續按下空格次數的例子:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
int count = 0;
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
count++;
}
if (Input.GetKeyUp(KeyCode.Space))
{
Debug.Log("您連續按"+count+"次空格");
count = 0;
}
}
}
結果:
任意鍵事件
Input.anyKeyDown
Input.anyKey
鼠標事件
按下事件
Input.GetMouseButtonDown()方法:檢測鼠標哪個按鍵被按下,返回參數是0(左鍵),1(中建),2(右鍵)
Input.mousePosition(得到鼠標當前座標)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("您按下鼠標左鍵,座標爲"+Input.mousePosition);
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("您按下鼠標中鍵,座標爲" + Input.mousePosition);
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("您按下鼠標右鍵,座標爲" + Input.mousePosition);
}
}
}
擡起事件:Input.GetMouseButtonUp()
對上述代碼進行補充:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("您按下鼠標左鍵,座標爲"+Input.mousePosition);
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("您按下鼠標中鍵,座標爲" + Input.mousePosition);
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("您按下鼠標右鍵,座標爲" + Input.mousePosition);
}
if (Input.GetMouseButtonUp(0))
{
Debug.Log("您擡起鼠標左鍵,座標爲" + Input.mousePosition);
}
if (Input.GetMouseButtonUp(1))
{
Debug.Log("您擡起鼠標中鍵,座標爲" + Input.mousePosition);
}
if (Input.GetMouseButtonUp(2))
{
Debug.Log("您擡起鼠標右鍵,座標爲" + Input.mousePosition);
}
}
}
運行結果:
注意:上述代碼將中鍵和右鍵寫反了,1是右鍵,2是中鍵。抱歉!!自己改一下就好了
長按事件:Input.GetMouseButton()
使用方法和鍵盤長按事件基本一致,略。