unity键盘事件与鼠标事件的简单使用

键盘事件

按下事件: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()
使用方法和键盘长按事件基本一致,略。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章