1. 程式人生 > >【Unity 3D學習】鍵盤控制人物在場景中移動

【Unity 3D學習】鍵盤控制人物在場景中移動

一、第一種情況,鍵盤左右鍵控制人物旋轉,讓人物可以面向四方,然後上下鍵控制移動。

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”,這個元件應該是和滑鼠點選地面事件相結合的。因為自己同時測鍵盤和滑鼠點選事件對人物移動的影響,所以才發生這樣的問題,特地記錄一下,找到原因的話再更。