How to Jump in Unity

Physics Based Character Controller part 3

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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Fizz Buzz Algorithm

You Never Thought That Owning An Upwork Clone Script Could Be So Beneficial!

Why is Clean Code Important?

Harnessing the Technological Age

Development Update for April 2nd, 2022

Change [in coding] can be scary!

Rails Bundle Install and Gemfile

TryHackMe - Kenobi Walkthrough

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tristan Engel

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.

More from Medium

Unity 2021 Object Pooling

Modelling Time in Unity

The Amazing Power of Light Probes

Setup Vuforia with Unity