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.

--

--

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