Unity开发备忘录000008:键盘交互

键盘操作

一. Input类

    Input类是Unity的输入类,里面封装了与输入相关的所有事件、属性和方法,如常用的键盘输入、鼠标输入、触摸输入等。

二. 键盘事件

    Input.GetKey(KeyCode.A)                   //按住键盘A键,返回为true

    Input.GetKeyDown(KeyCode.A)         //按下键盘A键,返回为true

    Input.GetKeyUp(KeyCode.A)             //抬起键盘A键,返回为true

三. 轴输入

    在输入设置中(dit → Project Settings → Input),系统预存了基于键盘操作的水平和垂直虚拟轴。

    Input.GetAxis("Horizontal");         //按左、右方向键及A、D键,获取水平轴的值 [-1,1]   

    Input.GetAxis("Vertical");             //按上、下方向键及W、S键,获取垂直轴的值 [-1,1]

四. 键盘键位码输入,改变对象坐标,实现对象的平移

    void myKeyboard()

    {    

        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))        

                transform.position += transform.forward * velocity;    

        if(Input.GetKey(KeyCode.S)||Input.GetKey(KeyCode.DownArrow))        

                transform.position+= -transform.forward * velocity;    

        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))        

                transform.position += -transform.right * velocity;    

        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))        

                transform.position += transform.right * velocity;

    }

五. 键盘轴输入,改变对象的速度,实现对象的平移

    void myAxes()

    {    

        float xMove = Input.GetAxis("Horizontal");    

        float yMove = Input.GetAxis("Vertical");    

        if (xMove < 0)        

                rigidbody.velocity = Vector3.left * velocity;    

        if (xMove > 0)        

                rigidbody.velocity = Vector3.right * velocity;    

        if (yMove < 0)        

                rigidbody.velocity = Vector3.back * velocity;    

        if (yMove > 0)        

                rigidbody.velocity = Vector3.forward * velocity;

    }

老孙头课堂:https://edu.csdn.net/lecturer/3617

工程源码下载:https://download.csdn.net/download/sunbowen63/11139123

猜你喜欢

转载自blog.csdn.net/sunbowen63/article/details/89148271