Unity 实用技巧 之 物体的旋转和移动控制
1、Input.GetAxis:
public static float GetAxis(string axisName);
Returns the value of the virtual axis identified by axisName.
The value will be in the range -1...1 for keyboard and joystick input. If the axis is setup to be delta mouse movement, the mouse delta is multiplied by the axis sensitivity and the range is not -1...1This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this value.
2、方法提要:
1)旋转
transform.Rotate (new Vector3(0, h * Time.deltaTime * rotateSpeed, 0));
2)移动
transform.Translate (new Vector3(v * Time.deltaTime * moveSpeed, 0, 0));
1、打开Unity,新建一个空工程,具体如下图
2、在场景中,新建一个“Plane”,和父子“Cube”,调小子“Cube”,并且把子“Cube”在“X”轴上移动些距离,具体如下图
3、新建一个“MoveRotateTest”脚本,双击脚本或者右键“Open C# Project”打开脚本,具体如下图
4、在打开的“MoveRotateTest”脚本上编写代码,首先设置变量,来设置移动和旋转速度,然后在Update函数里面“GetAxis”获得移动和旋转输入,最后把移动和旋转值传给与动物体,代码及代码说明如下图
5、“MoveRotateTest”脚本具体内容如下
using UnityEngine;
public class MoveRotateTest : MonoBehaviour {
public float moveSpeed = 5f;
public float rotateSpeed = 30f;
// Update is called once per frame
void Update () {
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");
transform.Translate (new Vector3(v * Time.deltaTime * moveSpeed, 0, 0));
transform.Rotate (new Vector3(0, h * Time.deltaTime * rotateSpeed, 0));
}
}
6、脚本编译正确,回到Unity界面,在场景中新建一个“GameObject”,把脚本“MoveRotateTest”赋给“GameObject”,可以适当调整移动旋转速度值,具体如下图
7、运行场景,水平键旋转,垂直键前后移动符合预期,具体如下图
8、到此,《Unity 实用技巧 之 物体的旋转和移动控制》讲解结束,谢谢