Why Does My Script Allow Double-Jumping?

Hello people, I’m trying to write a simple script to make my character jump on top of what is taught in Roll a Ball tutorial. I looked for some help in this website to write this jumping script but for some reason it’s allowing my player to doublejump. Any help would be appreciated :slight_smile:

Also does OnCollusionStay somehow “know” what is ground or does it simply turn back to true on any collusion event? How do I introduce e.g. “MyGroundPlane” GameObject to the code?


(Edit: Spelling.)

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

public class PlayerScript : MonoBehaviour {

    Rigidbody rb;
    public float speed;
    public float jumpForce;
    public Vector3 jump;
    public Vector3 movement;
    public bool isGrounded;

	void Start () {
        rb = GetComponent<Rigidbody>();
        speed = 10;
        jumpForce = 5;

    private void OnCollisionStay(Collision collision)
        isGrounded = true;

    void FixedUpdate () {

        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        movement = new Vector3(moveHorizontal * speed, 0, moveVertical * speed);

        jump = new Vector3(0, jumpForce, 0);
        if (Input.GetKeyDown("space") && isGrounded == true)
            rb.AddForce(jump, ForceMode.Impulse);
            isGrounded = false;

u can check if u had collision with the ground object by using tag
assign a tag to the ground object then compare if u really hit the right object:

  private void OnCollisionStay(Collision collision)
        if (collision.gameObject.tag =="your tag")
        isGrounded = true;

this way u are sure u hit the ground;

OnCollisionStay as it is right now, doesn’t care what you hit, it will set isGrounded to true, what I recommend is to add this in FixedUpdate and remove OnCollisionStay:

 isGrounded = Mathf.Abs(rb.velocity.y) < 0.1;

Thanks a lot for the answers! :slight_smile: