Jump in Unity 3D C#

Hello programmers, In this article, we will learn how to “Jump in Unity 3D”

Let’s get started with the building process

Jump in Unity 3D using Physics

  • Select your character
  • Add Rigidbody component to your character

      Inspector > Add Component > Rigidbody

  • Create a C# script named JumpScript
  • Write down the code given below
  • Attach this script to character GameObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JumpScript : MonoBehaviour
{

    public float speed = 10f;
    public Rigidbody rb;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector3(0, 5, 0);
        }
    }

}

Now the player is ready to jump.

Output

Press Spacebar to jump.

Prevent Mid Air Jump

The above script works perfectly and the character jumps perfectly. But there is a flaw you might have noticed that character can jump even in midair. In that case number of times, you press the spacebar key character will keep on jumping.

To prevent midair jumps we have to check if the character is jumping or not. If the character is jumping we return true, if not we will return to false.

We can use Collision detection to check if character is on ground.

JumpScript with isjumping check:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JumpScript : MonoBehaviour
{

    public float speed = 10f;
    public Rigidbody rb;
    private bool isJumping;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isJumping == false)
        {
            rb.velocity = new Vector3(0, 5, 0);
            isJumping = true;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        isJumping = false;
    }
}

Output

Leave a Reply

Your email address will not be published. Required fields are marked *