Jump Ability in my first game (2d platformer)

Can anybody tell me why this code isn’t working? I don’t get any errors, nothing happens when I press space. I am a beginner so please explain your answer. Thanks. Here is my code:

public class AbilityJump : MonoBehaviour {

public float jumpHeight;
private bool isJumping;
private Rigidbody2D RB2D;

private void Awake ()
{
	RB2D = GetComponent<Rigidbody2D> ();
}

private void Update ()
{
	if (Input.GetKeyDown (KeyCode.Space) && isJumping) 
	{
		RB2D.AddForce (Vector2.up * jumpHeight);
		isJumping = true;
	}
}

private void OnCollision2D (Collision col)
{
	if (col.gameObject.tag == "ground") // GameObject is a type, gameObject is the property
	{
		isJumping = false;
	}
}

}

In your Update method I think you want your if statement to have the condition !isJumping rather than isJumping. Here’s why:

  • The isJumping variable is a boolean, which has a default of false.
  • When you check isJumping in Update, it is still false, so the code inside the if is not executed.
  • But the code inside the if is the only thing in your script that would ever make isJumping true.

I think you mean !isJumping so you don’t end up adding more and more force while the player is in the air. As in:

public class AbilityJump : MonoBehaviour {

     public float jumpHeight;
     private bool isJumping;
     private Rigidbody2D RB2D;
     private void Awake ()
     {
         RB2D = GetComponent<Rigidbody2D> ();
     }
     private void Update ()
     {
         if (Input.GetKeyDown (KeyCode.Space) && !isJumping) 
         {
             RB2D.AddForce (Vector2.up * jumpHeight);
             isJumping = true;
         }
     }
     private void OnCollision2D (Collision col)
     {
         if (col.gameObject.tag == "ground") // GameObject is a type, gameObject is the property
         {
             isJumping = false;
         }
     }
}