simple jump

Hi guys, i try to code a simple jump on a cube, but with this code, it have 2 jump…

can you help me to retake this code for a simple jump please?

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour
{

public Vector3 jump;
public float jumpForce = 2.0f;

public bool isGrounded;
Rigidbody rb;
void Start()
{
rb = GetComponent();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}

void OnCollisionStay()
{
isGrounded = true;
}

void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{

rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
}

@zakilex , I think that your code is good, I created a sample project with a plane and a cube. Mesh collider on the plan, box collider, rigidbody and Jump component on the cube and got just one jump. Could you be getting a key bounce on your spacebar?

if you tap spacebar several time what append? only one jump?

it don’t work for me, there is multiple jumps…someone can help me?

Format your code please.

First: Apply your force in FixedUpdate, not Update.

Second: Set isGrounded to true in OnCollisionEnter() instead of OnCollisionStay() so your flag isn’t reset in between the physics engine update and your jump impulse.

1 Like

Hey,
Here you go This should work for you!!

One tip: If you want to show a code go to that little board type of thingy where it say insert and then click code.
It will give a much cleaner look to this thread.

Hope i was Usefull!

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour{

    public KeyCode jump;             //Which key need there be pressed (Change this in the Inspector)
    public float JumpHeight =5;      //JumpHeight
    public bool isGrounded;         

    Rigidbody rb;


    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKeyDown(jump))                                   //if you press the key
        {
            if (isGrounded == true)                                   //Check if you are on the ground if not it won't Do the commend bellow.
            {
                rb.velocity = new Vector3(0, JumpHeight, 0);          //Add Jump height
            }
        }
    }

    //-------------------------------------------------------------------
    //Check if Object IsGrounded
    void OnCollisionExit(Collision collisionInfo)                     //if you are not on the ground but in the air
    {
        isGrounded = false;
    }

    void OnCollisionEnter(Collision collisionInfo)                    //Wen you hit somthing
    {
        isGrounded = true;
    }

}