三、Unity中的鼠标、键盘的获取

  在Unity中,我们经常会处理点击鼠标的事件检测和键盘的事件检测。所以,我觉的应该将这个小知识点进行一个整理。

1.按下键盘的事件检测:

1.GetKey:   当通过名称指定的按键被用户按住时返回true ------ 持续按下,会一直触发按钮事件

2.GetKeyDown:   当用户按下指定名称的按键时的那一帧返回true。

3.GetKeyUp:   在用户释放给定名字的按键的那一帧返回true。  

4.GetAxis(“Horizontal”) 和 GetAxis(“Vertical”):   用方向键或WASD键来模拟-1到1的平滑输入。

using UnityEngine;
using System.Collections;

public class KeyInput : MonoBehaviour
{
    public KeyCode m_keycode_Q;
    public KeyCode m_keycode_E;
    public KeyCode m_keycode_R;
    public KeyCode m_keycode_F;

    void Start ()
    {
    
    }
    
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKey(m_keycode_Q))
        {
            Debug.Log("GetKey     Q;");
        }
        else if (Input.GetKeyDown(m_keycode_E))
        {
            Debug.Log("GetKeyDown     E;");
        }
        else if (Input.GetKeyUp(m_keycode_R))
        {
            Debug.Log("GetKeyUp     R;");
        }
        if (Input.GetAxis("Horizontal") != 0.0f)
        {
            Debug.Log(Input.GetAxis("Horizontal"));
        }
        if (Input.GetAxis("Vertical") != 0.0f)
        {
            Debug.Log(Input.GetAxis("Vertical"));
        }
        
    }
}

2.鼠标的判断:

1.GetMouseButton:

2.GetMouseButtonDown:

3.GetMouseButtonUp:

using UnityEngine;
using System.Collections;

public class GetMousess : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {
    
    }
    
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetMouseButton(0))
        {
            Debug.Log("GetMouseButton  Mouse 0");
        }
        else if (Input.GetMouseButtonDown(1))
        {
            Debug.Log("GetMouseButtonDown  Mouse 1");
        }
        else if (Input.GetMouseButtonUp(2))
        {
            Debug.Log("GetMouseButtonUp  Mouse 2");
        }
    }
}

3.通用于鼠标和键盘的事件检测:

1.GetButton:   根据按钮名称返回true当对应的虚拟按钮被按住时 ------ 持续按下,会一直触发按钮事件

2.GetButtonDown:   在给定名称的虚拟按钮被按下的那一帧返回true。 

3.GetButtonUp:   在用户释放指定名称的虚拟按钮时返回true。  

using UnityEngine;
using System.Collections;

public class MouseInput : MonoBehaviour
{
    public KeyCode keyQ;

    void Start ()
    {
    
    }

    void Update ()
    {
        //可以检测到鼠标的点击事件:
        //1.Fire1 ---> 鼠标左键
        //2.Fire2 ---> 鼠标右键
        //3.Fire3 ---> 鼠标中键
        if (Input.GetButton("Fire1"))
        {
            Debug.Log("GetButton  Mouse 0");
        }
        else if (Input.GetButtonDown("Fire2"))
        {
            Debug.Log("GetButtonDown  Mouse 1");
        }
        else if (Input.GetButtonUp("Fire3"))
        {
            Debug.Log("GetButtonUp  Mouse 2");
        }

        //1.Jump ---> 键盘的空格键
        if (Input.GetButton("Jump"))
        {
            Debug.Log("GetButton  Jump");
        }

    }
}

 

posted @ 2016-11-24 14:04  Dean二十七  阅读(1082)  评论(0编辑  收藏  举报