How to jump in a 2d Unity Game

If you are making a 2d unity project, whether it be a platformer or another type of game, jumping is a common mechanism.

Lets start by creating an empty C# class called PlayerJump.

using UnityEngine;
using System.Collections;

public class PlayerJump : MonoBehaviour {
  
}

In this C# class, lets first grab the rigid body which allows our character to move around.

Also, lets create a jumpSpeed variable that will stand for how much upward velocity our character will jump with. By making this variable public, we can change the jump force of our character in the unity inspector.

using UnityEngine;
using System.Collections;

public class PlayerJump : MonoBehaviour {
  public float jumpSpeed = 10f;
  
  void Start() {
    rigidbody = GetComponent<Rigidbody2D>(); 
  }

}

Next, lets create a jump function and add the jump function so that it is called in the update function each frame.

void Update(){
  Jump()
}

void Jump(){
  // TODO
}

We don’t have any code in our jump function right now so our character won’t be able to jump just yet.

Now, lets fill in our. jump function.

void Jump(){
  if(Input.GetButtonDown("Jump"){
    Vector2 jumpVelocityToAdd = new Vector2(0f, jumpSpeed);
    rigidbody.velocity += jumpVelocityToAdd;
  }
}

We use input get button down function to check when the user presses the jump button. When they press the jump button we will create a jumpVelocityToAdd vector2 and then set the velocity of the rigidbody to that variable.

The entire class is shown below. Try customizing the jumpSpeed variable to vary the amount of jump our character can have.

using UnityEngine;
using System.Collections;

public class PlayerJump : MonoBehaviour {
  public float jumpSpeed = 10f;
  
  void Start() {
    rigidbody = GetComponent<Rigidbody2D>(); 
  }


  void Update(){
    Jump()
  }

  void Jump(){
    if(Input.GetButtonDown("Jump"){
      Vector2 jumpVelocityToAdd = new Vector2(0f, jumpSpeed);
      rigidBody.velocity += jumpVelocityToAdd;
    }
  }

}

https://www.googletagmanager.com/gtag/js?id=UA-63695651-4