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



我让角色可以向 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 已经为您计算了这些角度和旋转。

若要跳转,可能需要为跳转操作分配一个按钮。然后,您可以检查是否Update每帧都按下了跳转按钮。 您可以使用类似的东西并将其添加到代码中的 movement 命令中:

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);
}

最新更新