Unity控制物体移动旋转

Unity控制物体移动旋转

首先,在Unity的Hierarchy中创建一个新的立方体Cube,命名为Player,然后在Assets中创建新的文件夹(Folder)以存放脚本文件,命名为Scripts,随后在Scripts文件夹下创建 C# script文件,按F2重命名为PlayerMove,打开PlayerMove文件,输入如下代码:

public class PlayerMove : MonoBehaviour
{

//定义移动的速度
public float MoveSpeed = 2f;
//定义旋转的速度
public float RotateSpeed = 2f;


void Start()
{

}

void Update()
{

    //如果按下W或上方向键
    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
    {
        //以MoveSpeed的速度向正前方移动
        this.transform.Translate(Vector3.forward * MoveSpeed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
    {
        this.transform.Translate(Vector3.back * MoveSpeed * Time.deltaTime);
    }

    //如果按下A或左方向键
    if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    {
            //以RotateSpeed为速度向左旋转
            this.transform.Rotate(Vector3.right * RotateSpeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    {
            this.transform.Rotate(Vector3.left * RotateSpeed * Time.deltaTime);
        }

}
}

在VS2017里保存编译,随后在Unity里将该C#文件拖到Player对象上,建立连接。双击Player对象,在Inspector里会显示该脚本文件的参数信息,该信息为移动速度和旋转速度。点击播放,即可用上下左右键控制平移旋转。

你可能感兴趣的:(Unity)