【Unity 3D学习】键盘控制人物在场景中移动

1、第一种状况,键盘左右键控制人物旋转,让人物能够面向四方,而后上下键控制移动。spa

public float speed = 3.0F;
public float rotateSpeed = 3.0F;
CharacterController controller;
void Start () {
     controller = GetComponent<CharacterController>();
}
void Update() {
     transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);
     Vector3 forward = transform.TransformDirection(Vector3.forward);  //注意这个方法
     float curSpeed = speed * Input.GetAxis("Vertical");
     controller.SimpleMove(forward * curSpeed);
}
第二种状况,键盘四个键能够同时控制人物移动。

public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
CharacterController controller;
void Start () {
     controller = GetComponent<CharacterController>();
}
void Update() {
     if (controller.isGrounded) {
          moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
          moveDirection = transform.TransformDirection(moveDirection);
          moveDirection *= speed;
          if (Input.GetButton("Jump"))
               moveDirection.y = jumpSpeed;
     }
     moveDirection.y -= gravity * Time.deltaTime;
     controller.Move(moveDirection * Time.deltaTime);
}


ps:这里使用了组件“Character Controller”,要注意的是使用了这个以后好像会和组件“Nav Mesh Agent”冲突。因此使用键盘调试的时候不要使用“ Nav Mesh Agent”,这个组件应该是和鼠标点击地面事件相结合的。由于本身同时测键盘和鼠标点击事件对人物移动的影响,因此才发生这样的问题,特意记录一下,找到缘由的话再更。