定义
public static float GetAxisRaw(string axisName);
描述
Returns the value of the virtual axis identified by axisName with no
smoothing filtering applied.The value will be in the range -1…1 for keyboard and joystick input.
Since input is not smoothed, keyboard input will always be either -1,
0 or 1. This is useful if you want to do all smoothing of keyboard
input processing yourself.
例子
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
float speed = Input.GetAxisRaw("Horizontal") * Time.deltaTime;
transform.Rotate(0, speed, 0);
}
说明
1)axisName表示轴的名称,可选内容为’Horizontal(水平)’以及’Vertical(垂直)’,可在unity->edit->project settings 中查看。
2)根据键盘按键返回-1,0,1,实现角色移动。
定义
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…1.This is frame-rate independent; you do not need to be concerned about
varying frame-rates when using this value
例子
public class ExampleClass : MonoBehaviour {
public float speed = 10.0F;
public float rotationSpeed = 100.0F;
void Update() {
float translation = Input.GetAxis("Vertical") * speed;
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
translation *= Time.deltaTime;
rotation *= Time.deltaTime;
transform.Translate(0, 0, translation);
transform.Rotate(0, rotation, 0);
}
}
说明
通过按键返回-1,0,1,与GetAxisRaw不同的是,返回值逐渐增加,可用于赛车的加速的减速。
void FixedUpdate()
{
float h = Input.GetAxisRaw("Horizontal");//获取水平方向移动
float v = Input.GetAxisRaw("Vertical");//获取垂直方向移动
Move(h, v);//角色移动
Turning();//角色转向
Animating(h, v);//动画
}
void Move(float h,float v)
{
movement.Set(h, 0f, v); //vector3向量
movement = movement.normalized * speed * Time.deltaTime; //movement.normalized使向量单位化,结果等于每帧角色移动的距离
playerRigidbody.MovePosition(transform.position + movement);//设置刚体移动位置
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);//定义射线检测鼠标位置
RaycastHit floorHit; //光线投射碰撞
if (Physics.Raycast(camRay,out floorHit, camRayLength, floorMask))
//光线投射,计算在指定层上是否存在碰撞,返回bool
{
Vector3 playerToMouse = floorHit.point - transform.position;//计算差值
playerToMouse.y = transform.position.y;//不改变y轴方向
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
//四元数用于表示旋转,创建一个旋转,沿着forward(z轴)并且头部沿着upwards(y轴)的约束注视
playerRigidbody.MoveRotation(newRotation);
}
}
void Animating(float h,float v)
{
bool walking = h != 0f || v != 0f;
anim.SetBool("IsWalking", walking);//设置动画状态
}