我让角色在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
你的跳跃按钮是否在每一帧中被按下。你可以使用类似这样的东西,并将其添加到你的代码中的移动命令中。
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);
}