Menu
CoddyTech

Recap: Double Jump

Part of the Building Real Games section of Coddy's Unity journey. Lesson 43 of 60.

This chapter moved a CharacterController by hand: Move for the walk, gravity kept in a field, and jumps worked out from their height. The hero adds one more jump in the air.

challenge icon

Challenge

Medium

Give the hero a jump and one air jump. The walk is written.

  1. First, while grounded: airJumpUsed = false, and a falling verticalSpeed becomes -2f.
  2. On Input.GetButtonDown("Jump"): grounded, verticalSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);; else, if !airJumpUsed, the same with airJumpHeight, and set airJumpUsed.
  3. Then add gravity * Time.deltaTime to verticalSpeed.

Press Play and double jump onto the ledge. Then Check.

Try it yourself

using UnityEngine;

public class Hero : MonoBehaviour
{
    public float speed = 5f;
    public float gravity = -25f;
    public float jumpHeight = 2f;
    public float airJumpHeight = 1.28f;

    CharacterController controller;
    float verticalSpeed;
    bool airJumpUsed;

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

    void Update()
    {
        // Reset on the ground, jump or air jump on Space, then add gravity

        Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) * speed;
        move.y = verticalSpeed;
        controller.Move(move * Time.deltaTime);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games

Practice on your own: Unity playground