Menu
CoddyTech

跳跃

Coddy Unity 游戏:天空赛道 课程的第 3 课,共 21 课。

接下来,跑步者会跳跃。CharacterController 本身没有重力:你的脚本会记录垂直速度,并在每一帧根据这个速度移动。

重力会在每一帧改变这个速度。当跑步者站在地面上时(controller.isGrounded),将向下速度保持在较小的 -2,这样它就会一直贴在道路上:

if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;

在重力 g 的作用下,要达到高度 h,跳跃开始时的速度应为 Mathf.Sqrt(h * -2f * g)。跳跃高度为 1.6,重力为较大的 -40 时,跑步者会跳得很高,并快速落下,这很适合障碍物朝你迎面而来的游戏:

bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
    fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
}

现在,移动量还包括 y 方向的部分:fallSpeed * Time.deltaTime。

challenge icon

挑战

简单

让 runner 跳起来。

  1. 在 Runner 中添加 public float jumpHeight = 1.6f;、public float gravity = -40f; 和 private float fallSpeed;。
  2. 在车道按键之后,读取跳跃按键(W、Up、Space),并且只在 controller.isGrounded 为 true 时跳跃。
  3. 在 targetX 之前,添加上面的两行重力代码。
  4. 将移动向量改为 new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f)。

按“开始”,然后按 W 或 Space:runner 会跳起并落地。接着按“检查”。

亲手试试

using UnityEngine;

public class Runner : MonoBehaviour
{
    public float laneWidth = 2.5f;
    public float laneSpeed = 16f;

    public int lane;

    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);

        float targetX = lane * laneWidth;
        float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
        Vector3 move = new Vector3(x - transform.position.x, 0f, 0f);
        controller.Move(move);
    }
}

Unity 游戏:天空赛道中的所有课

自己练习: Unity 在线编辑器