How to make a character jump in Unity

Jump is one of the most used features in games. So, if you are learning game development you need to know how to make your player jump. There are two major ways to make an object jump. The first one is to use physics and the second method is to use animation. It totally depends on your game type whether you should use physics or animation to jump.

The general rule is, if your character movements in the game do not satisfy physics law then you should use animation to make the character jump. In this tutorial, we will walk you through the steps to implement jump using physics and animation.

If you are using a character controller then read our tutorial on Unity character controller to make your player jump.

Jump in Unity using physics

Simple jump with Space bar

We will add a Ridigbody component and apply upward force to it when space bar is pressed. Here are the steps to do it.

  1. Create a new script called “Character_jump” by right clicking on the project window and going to create>new C# script.
  2. Copy and paste the code below to the script.
  3. Click on Add component and add a Rigidbody component to your character.
  4. Attach the script to your character.
  5. Set your jump force value in the inspector window.
  6. Your character is ready to jump.
Rigidbody component and the script attached to the character.

Unity simple Jump script

using UnityEngine;
public class Character_jump : MonoBehaviour
{
    public float jumpforce = 10f;
    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.AddForce(Vector3.up * jumpforce,ForceMode.Impulse);
                
            }
        
    }
    
}

In the above script, we take the jump force and multiply it with the upward direction(Vector3.up) before applying to the Rigidbody. If your character’s upward direction is not aligned with the Y axis then you should use transform.up in place of Vector3.up.

Avoiding Mid Air jump with Ground check in Unity

The above script works flawlessly but the character can jump even in midair. If you don’t want your character to jump in midair you need to check if the character is standing on the ground.

There are different ways to ground check. The first option is collision detection but a collision can happen even if the player is upside down or if is lying on the ground.

The other options are Height offset, Raycast and Boxcast. The below image explains scenarios where height offset and Raycast won’t work.

Boxcast or Spherecast with a layermask is the best way to ground check in Unity.

Image explaining the different scenarios of Ground check.

Check if the player is grounded using Boxcast.

  1. Create a new layer for the ground. We will use using it for the Boxcast.
  2. Assign the layer to your ground object.
  3. Add the script below to your character and set the size of box, max distance and layerMask as explained below.

The size of the box should be smaller than the height and width of the player. If the box is touching the ground at initial position, it will not detect the ground.

Guide to select the correct box size.

Set the max distance to a value light higher than (Character height/2). That’s because, the Boxcast will start from the center of the character. The image below will help you decide on the max distance.

Selecting the right max distance

Unity Jump script 3D

Jump script with ground check using Boxcast. You can also use Spherecast in the same way.

using UnityEngine;
public class Character_jump : MonoBehaviour
{
    Rigidbody rb;
    public Vector3 boxSize;
    public float maxDistance;
    public LayerMask layerMask;
    public float jumpforce = 10f;

    // Start is called before the first frame update
    void Start()
    {
        rb=GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        
        if(Input.GetKeyDown(KeyCode.Space) && GroundCheck())
        {
            rb.AddForce(transform.up*jumpforce,ForceMode.Impulse);
        }        
        
    }
    void OnDrawGizmos()
    {
        Gizmos.color=Color.red;
        Gizmos.DrawCube(transform.position-transform.up*maxDistance,boxSize);
    }
    bool GroundCheck()
    {
        if(Physics.BoxCast(transform.position,boxSize,-transform.up,transform.rotation,maxDistance,layerMask))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
     
    
}

Unity Jump script 2D with ground check

using UnityEngine;
public class Character_jump : MonoBehaviour
{
    Rigidbody2D rb;
    public Vector3 boxSize;
    public float maxDistance;
    public LayerMask layerMask;
    public float jumpforce = 10f;

    // Start is called before the first frame update
    void Start()
    {
        rb=GetComponent<Rigidbody2D>();
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if(Input.GetKeyDown(KeyCode.Space) && GroundCheck() )
        {
            rb.AddForce(transform.up*jumpforce,ForceMode2D.Impulse);
        }
        
    }

    void OnDrawGizmos()
    {
        Gizmos.color=Color.red;
        Gizmos.DrawCube(transform.position-transform.up*maxDistance,boxSize);
    }
    private bool GroundCheck()
    {
        if(Physics2D.BoxCast(transform.position,boxSize,0,-transform.up,maxDistance,layerMask))
        {
            return true;
        }
        else{
            return false;
        }
    }
    
}

Both 3D and 2D script above uses the old input system to get the space key. If you are using the new input system, then check out our tutorial on basics of new input system.

Controlling Jump height and fall

We can control the jump height by changing the jump force. But the speed at which the object will fall down depends on the mass and gravity set in the Rigidbody component. Changing gravity will affect other objects in the game.

So, you can increase or decrease the mass of your game object to control the speed of fall. You also need to change the jump force to achieve the same jump height as earlier after you have changed the mass.

Mass set inside the Rigidbody component in Unity

Recommended Asset

You can get this Physics based character controller from the Unity Asset store if you don’t want to code. It contains all the required features that you need in a 3D character controller. The player can easily interact with the physical environment, move and push objects, slide on surfaces, climb, wall jump and so on.

Implement jump with Animation

Implementing jump with animation is recommended for non-physics games. But there are a few drawbacks of this method.

  1. You cannot change the height of jump during the game.
  2. Jump looks unnatural.

This doesn’t mean there are only disadvantages. You can control the speed of animation which in turn controls the time required for the jump. This control is not available with physics.

Animating character to simulate jump

  1. Open the animation window by going to window>Animation>Animation.
  2. Select your character in the hierarchy window and click create new animation on the Animation window.
  3. Save the animation as “Player_jump”.
  4. This will create an Animation clip and add an Animator component to the character.
  5. Click the record button on the Animation window. Don’t change anything on the Animation window without selecting the record button. If you do then the changes will not be saved.
  6. Set the player to ground position for the first and the last keyframes.
  7. Select the middle keyframe and set the character position for the highest position jump point.
  8. Click on the Curves tab on the bottom of the Animation window.
  9. Use the Animation curve to make the jump animation look natural.
  10. Click on the Animation name and select create new.
  11. Create another empty animation clip called Rest. This will be our default state.
Animation window

Making the character Jump

While creating Animation, Unity would have added the Animator component to the Player.

  • Select the animation clip in the project window and uncheck loop time.
  • Select the character in the Hierarchy window.
  • Open the Animator window by going to Window>Animation>Animator.
Setting Rest as default state
  • You should see the animation clips inside the Animator. If not, drag and drop the animation clip “Player_jump” and “Rest” to animator window.
  • Add the script below to play the animation when space bar is pressed.

Animator window setting

  1. Set rest clip as the default state by right clicking on the Animation state.
  2. Make a transition from “Player_jump” to “Rest”. Select the transition line and check “has exit time”.
Transition from Jump state to Rest with exit time as condition.

Script to play the jump animation when space bar is pressed

using UnityEngine;

public class Character_jump : MonoBehaviour
{

    Animator anim;

    void Start()
    {
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        if (Input.GetButtonDown("Jump"))
            {
                anim.Play("Player_jump");
                
            }
        
    }

    
}

You can control the animation speed by selecting the Animation state and setting the speed parameter.

You don’t have to check for ground in case of animation as the “Player_jump” animation ends with the player on the ground.

If you have any other questions on player jump, leave them in the comments below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading