首页 > 解决方案 > 如何使用字符控制器在 Unity3d 的 C# 脚本中添加“跳转”?

问题描述

我让角色可以朝 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);
        }
    }
}

标签: c#windowsunity3dgame-development

解决方案


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

要跳跃,您可能需要为跳跃动作分配一个按钮。然后,您可以检查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);
 }

推荐阅读