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

Cloud costs aren’t actually dropping dramatically

Boxing to share data in Swift

The 5 Best Visual Studio Code Extensions

computer

Tees: Where and How to Use

Evaluating Docker Desktop 4.6’s new VirtioFS file sync on macOS

VirtioFS accelerated directory sharing in Docker Desktop 4.6

Implementing a Cache Invalidation in Distributed Cache Engine: LRU [With Code Implementation]

Hello Container

Google’s Next Big Thing

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

2.5D Platformer

Unity 2021 Object Pooling — Part II

VulnHub: MoneyHeist: Catch Us If You Can