將如下代碼添加到角色攝像機:html
public Transform player; // 在這裏添加玩家角色. private float mouseX, mouseY; // 儲存鼠標移動的值. private float xRotation; // 儲存X軸的旋轉. public float Sensitivity; // 鼠標靈敏度. private void Update() { // 獲取鼠標移動的值. mouseX = Input.GetAxis("Mouse X") * Sensitivity * Time.deltaTime; mouseY = Input.GetAxis("Mouse Y") * Sensitivity * Time.deltaTime; // 控制X軸的旋轉. xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -70, 70); // 控制Y軸的旋轉. player.transform.Rotate(Vector3.up * mouseX); transform.localRotation = Quaternion.Euler(xRotation, 0, 0); }
首先,確保你的角色已經添加了角色控制器,並且它的範圍覆蓋了角色本體。
在角色中添加一個空物體,起名爲GroundChenck,並將它移動到角色最下面的位置。
將如下代碼添加到角色:3d
private CharacterController playerController; // 玩家角色控制器. public Transform groundCheck; // 地面檢測點. private Vector3 direction; // 方向. private Vector3 velocity; // 加速度. private float horizontal, vertical; // 儲存鍵值. public float moveSpeed; // 移動速度. public float jumpSpeed; // 起跳速度. public float gravity; // 重力. public float checkRadius; // 地面檢測點半徑. private bool onGround; // 是否在地面上. private void Start() { playerController = GetComponent<CharacterController>(); // 實例化玩家角色控制器. } private void Update() { // 檢測角色是否碰到地面. onGround = Physics.CheckSphere(groundCheck.position, checkRadius); // 加速度歸零. if (onGround && velocity.y < 0) { velocity.y = 0f; } // 賦值鍵值. horizontal = Input.GetAxis("Horizontal") * moveSpeed; vertical = Input.GetAxis("Vertical") * moveSpeed; // 角色移動. direction = transform.forward * vertical + transform.right * horizontal; playerController.Move(direction * Time.deltaTime); // 角色跳躍. if (Input.GetButtonDown ("Jump") && onGround) { velocity.y = jumpSpeed; } // 重力加速度. velocity.y -= gravity * Time.deltaTime; playerController.Move(velocity * Time.deltaTime); }