首先介绍Input.GetAxis方法,官方文档给出的解释为:
//Returns the value of the virtual axis identified by axisName.
//返回根据参数名所指定的虚拟轴上的数值。
public static float GetAxis(string axisName)
即根据输入的axisName,返回输入设备在axisName(可能是某一个虚拟轴)上的位移量。这里的位移量指的是相邻两次GetAxis方法被调用时所产生的位移量。即,如果每帧调用一次该方法,就会返回axisName在该帧的位移量。
其中,axisName的可选参数如下:
类型 |
axisName参数值 |
解释 |
触屏类 |
“Mouse X” |
鼠标沿着屏幕X移动时触发 |
|
“Mouse Y” |
鼠标沿着屏幕Y移动时触发 |
|
“Mouse ScrollWheel” |
当鼠标滚动轮滚动时触发 |
键盘操作类 |
“Vertical” |
对应键盘上面的上下箭头,当按下上或下箭头时触发 |
|
“Horizontal” |
对应键盘上面的左右箭头,当按下左或右箭头时触发 |
得到输入后,可以根据输入值进行物体运动的控制,首先介绍transform.Translate方法:
//Moves the transform by x along the x axis, y along the y axis, and z along the z axis.
//根据relativeTo所指定的坐标空间或transform空间进行x、y、z轴的相应移动,relativeTo可省略,默认为物体自身
public void Translate(Vector3 translation, Space relativeTo = Space.Self);
public void Translate(float x, float y, float z, Space relativeTo = Space.Self);
public void Translate(Vector3 translation, Transform relativeTo);
public void Translate(float x, float y, float z, Transform relativeTo);
示例,如
//导弹相对于战斗机Fighter以ShootSpeed 的速度向前运动,Vector3.forward在此时表示导弹的正前方
transform.Translate(Vector3.forward * ShootSpeed * Time.deltaTime, Fighter.transform);
同理,也有控制目标物体旋转值的方法:
public void Rotate(Vector3 eulerAngles, Space relativeTo = Space.Self);
public void Rotate(float xAngle, float yAngle, float zAngle, Space relativeTo = Space.Self);
public void Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self);
另一种改变物体运动的方式是为其施加某种力:
public void AddForce(float x, float y, float z, ForceMode mode = ForceMode.Force);
public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force);
示例为Unity官网Roll-A-Ball示例中,利用键盘控制小球运动的方法:
public float speed;
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
GetComponent<RigidBody>().AddForce(movement * speed * Time.deltaTime);
}