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
MediumGive the hero a jump and one air jump. The walk is written.
- First, while grounded:
airJumpUsed = false, and a fallingverticalSpeedbecomes-2f. - On
Input.GetButtonDown("Jump"): grounded,verticalSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);; else, if!airJumpUsed, the same withairJumpHeight, and setairJumpUsed. - Then add
gravity * Time.deltaTimetoverticalSpeed.
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);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank8Character Controller
CharacterController.MoveGravity by HandJumpingPushing ThingsMove Where You LookRecap: Double Jump3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground