如何使用角色控制器在 Unity3d 的 C# 脚本中添加 "jump"?

How to add "jump" in C# script in Unity3d using Character Controller?

我让角色可以在 8 个方向上行走,但我不知道如何添加“跳跃”才能使一切正常...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    public CharacterController controller;
    public float speed;
    float turnSmoothVelocity;
    public float turnSmoothTime;

    void Update() {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if (direction.magnitude >= 0.1f) {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f); 
            controller.Move(direction * speed * Time.deltaTime);
        }
    }
}

不需要计算角色的角度和旋转,因为当您使用 CharacterController 时,Unity 已经为您计算了这些 class。

要跳转,您可能需要为跳转分配一个按钮action.Then,您可以检查Update您的跳转按钮是否在每一帧都被按下。 您可以使用类似这样的东西并将其添加到代码中的移动命令中:

 public float jumpSpeed = 2.0f;
 public float gravity = 10.0f;
 private Vector3 movingDirection = Vector3.zero;

 void Update() {
     if (controller.isGrounded && Input.GetButton("Jump")) {
         movingDirection.y = jumpSpeed;
     }
     movingDirection.y -= gravity * Time.deltaTime;
     controller.Move(movingDirection * Time.deltaTime);
 }