using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public Animator anim; public CharacterController characterController; public float jumpPower; private Vector3 velocity; public float moveSpeed = 5.0f; public float rotateSpeed = 50.0f; void Start() { anim = GetComponent(); characterController = GetComponent(); } void Update() { bool isRun = Input.GetKey(KeyCode.LeftShift); //檢查是否按下 Shift float h = isRun ? Input.GetAxis("Horizontal") : Input.GetAxis("Horizontal") * 0.5f; //取得目前的移動速度 float v = isRun ? Input.GetAxis("Vertical") : Input.GetAxis("Vertical") * 0.5f; //取得目前的移動速度 //檢查是否按下 Shift anim.SetFloat("Speed", v, 0.2f, Time.deltaTime); anim.SetFloat("Turn", h, 0.2f, Time.deltaTime); // 設置水平移動速度,避免角色只能朝 Z 軸方向移動 Vector3 horizontalVelocity = transform.forward * (v * moveSpeed); //抓取角色正前方的位置 velocity.x = horizontalVelocity.x; //在速度中增加 X 與 Z 軸 velocity.z = horizontalVelocity.z; velocity.y += Physics.gravity.y * Time.deltaTime; //在速度中增加重力 characterController.Move(velocity * Time.deltaTime); //讓角色控制器移動 transform.Rotate(0, h * rotateSpeed * Time.deltaTime, 0); //讓角色控制器旋轉 if (Input.GetButtonDown("Jump")) { velocity.y = Mathf.Sqrt(jumpPower * -2.0f * Physics.gravity.y); //計算初始垂直速度(Mathf.Sqrt = 計算一個數字的平方根) } } } // 這是 V2 版本