Simple Jump Script Help

Hi Guys,
I have a problem with my very simple jump script. Basicly i can jump, but before i land i can still keep junping. so when i press space before me player lands if i press space again he will keep jumping for ever. Please help me i am new to c#.

Thank You

using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour {
	public float jumpPower = 1;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown("Jump")) {
			rigidbody2D.AddForce(transform.up*jumpPower);
		}
	
	}
}

use a bool to see if jumping if(jumping) { //dont allow jump } else { //jumping is good }

–

i dont get what you mean should i change from float to bool? im a begginer

–

1 Answer

1

Use a variable to determine if your player is on the ground, and determine if it is true by using OnCollisionStay, like this:

using UnityEngine;
using System.Collections;
 
public class Jump : MonoBehaviour {
    public boolean grounded = true;
    public float jumpPower = 1;
    // Use this for initialization
    void Start () {
 
    }
 
    // Update is called once per frame
    void Update () {
       if (Input.GetButtonDown("Jump") && grounded == true) {
         rigidbody2D.AddForce(transform.up*jumpPower);
       }
 
    }
}

void OnCollissionEnter(){
    grounded = true;
}
void OnCollissionExit(){
    grounded = false;
}

and that will work better than checking if your jumping, because if he’s falling he isnt jumping but you still shouldnt be able to jump.

it didnt work i can still jump more when im in the air

–

Collision is spelled wrong and you should set grounded to false in the jump if clause.

–

the answer is good, but just disable the grounded in case you jumped if (Input.GetButtonDown("Jump") && grounded == true) { rigidbody2D.AddForce(transform.up*jumpPower); grounded = false; }

–

when the ground is set false the player cant jump.

–

everything is great thank you. but when i land i cant jump again

–