unity学习笔记(二)——键盘、鼠标事件

  1. 键盘事件

  1. 按下事件

void Update () {
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("您按下了A键");
        } 
        if (Input.GetKeyDown(KeyCode.B))
        {
            Debug.Log("您按下了B键");
        }
        if (Input.GetKeyDown(KeyCode.Backspace))
        {
            Debug.Log("您按下了退格键");
        }
        if (Input.GetKeyDown(KeyCode.F1))
        {
            Debug.Log("您按下了F1键");
        }
        if (Input.GetKeyDown(KeyCode.Alpha0))
        {
            Debug.Log("您按下了0键");
        }
    }
  1. 抬起事件

#region 抬起事件 
        if (Input.GetKeyUp(KeyCode.A))
        {
            Debug.Log("您抬起了A键");
        }
        if (Input.GetKeyUp(KeyCode.B))
        {
            Debug.Log("您抬起了B键");
        }
        if (Input.GetKeyUp(KeyCode.Backspace))
        {
            Debug.Log("您抬起了退格键");
        }
        if (Input.GetKeyUp(KeyCode.F1))
        {
            Debug.Log("您抬起了F1键");
        } 
        #endregion
  1. 长按事件

  #region 长按事件 
        int count = 0;
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("A按下一次");
        }
        if (Input.GetKey(KeyCode.A))
        {
            count++;
            Debug.Log("A被连续按了:"+count);
        }
        if (Input.GetKeyUp(KeyCode.A))
        {
            //抬起后清空帧数
            count = 0;
            Debug.Log("A按键抬起");
        }
        #endregion
  1. 鼠标事件

//1、按下事件
Input.GetMouseButtonDown()
//来判断鼠标哪个按键被按下:
//如果参数为0,则代表鼠标左键被按下,
//参数为1代表鼠标右键被按下,
//参数为2代表鼠标中键被按下

//2、抬起事件
Input.GetMouseButtonUp()
//方法监听鼠标按键的抬起事件

//3、长按事件
Input.GetMouseButton()
//方法监听鼠标某个按键是否一直处于按下状态。

//4、鼠标所在的屏幕坐标
Input.mousePosition
  1. 鼠标点击后物体移动到鼠标位置

if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if(Physics.Raycast(ray,out hit))
            {
                Vector3 point = hit.point;
                transform.position = point;
            }
        }

猜你喜欢

转载自blog.csdn.net/ximi2231/article/details/129519273