Why does my player keep double juming to the sky?

Hi guys,

I am making a 2D platformer game and i have programmed a the controls for the player but i have one issue that is bothering me. It is the jump issue which is the player can keep jumping.

Any help would be greatly appreciated.


using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	public float speed;
	public float jump;
	float moveVelocity;
	//Grounded Vars
	bool grounded = true;
	void Update ()
		if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKeyDown (KeyCode.Z) || Input.GetKeyDown (KeyCode.W))
				GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
		moveVelocity = 0;
		//Left Right Movement
		if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A))
			moveVelocity = -speed;
		if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D))
			moveVelocity = speed;
		GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D> ().velocity.y);
	//Check if Grounded
	void OnTriggerEnter2D()
		grounded = true;
	void OnTriggerExit2D()
		grounded = false;

Do you have a gravity variable? It looks like you’re never decreasing the players Y velocity, try adding this:

// Put this at the top with your variables. Adjust in inspector to get gravity right
public float gravity = 2f;

// Change line 37 to this

float g = GetComponent<Rigidbody2D> ().velocity.y;

g -= gravity;

if(grounded) g = 0;

GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, g);

What happens is that you set grounded = true, and then nothing sets it false. So character thinks he’s always grounded, and hence you can jump even in air.

You should use a different method to check if character is grounded. Instead of checking for trigger, use collision (OnCollisionEnter2D and OnCollisionExit2D) Or use a Raycast.