How to Jump in Unity

Physics Based Character Controller part 3

Tristan Engel
1 min readDec 31, 2021

In this article we will focus on making our player able to jump.

If we just apply the jumpheight to velocity height it the jump won’t work as expected. To make this work we need a cached velocity for Y. Other wise it will be reset to zero every frame update, when we set our direction based on the horizontal input.

Jump Script

//config
private float _speed = 5f;
private float _gravity = 0.5f;
private float _jumpHeight = 25f;

private float _yVelocity;

void Start()
{
_controller = GetComponent<CharacterController>();
if (_controller == null) { Debug.LogError("player.charactercontroller is null"); }
}


void Update()
{
//get horizontal input = direction
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0);
//velocity = direction with speed
Vector3 velocity = direction * _speed;
if (_controller.isGrounded == true)
{
//jump
if (Input.GetAxis("Jump") > 0)
{
_yVelocity = _jumpHeight;
}

}
else
{
_yVelocity -= _gravity;
}

velocity.y = _yVelocity;

//move player with velocity
_controller.Move(velocity * Time.deltaTime);
}

We don’t add (+=) jumpheight, because we need to reset y velocity cache.

--

--

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.