Jump problem

Hi, I am having trouble making a jump which allows the player to either hold the screen to jump continuously or tap the screen once and just jump once. My script below is what I am using but since GetMouseButton(0) is being called more than once while the player is on the ground the rigid body is getting the force added more than once too which means the player flies way up into the air. Is there a way which I can call the rigidbody.AddForce() just once using this method or will I need to use a different method? thanks

    var jump : boolean;
    var grounded : boolean = false;
    var groundCheck : Transform;
    var groundRadius : float = 0.2f;
    var whatIsGround : LayerMask;
var myRigidbody : Rigidbody2D;
    
    function FixedUpdate(){
    	grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    }
    
    function Update(){
    	if(Input.GetMouseButton(0)){
    		if(grounded){
    			jump = true;
    		}	
    	}
    	if(jump){
    		myRigidbody.AddForce(new Vector2(0, 1500f * Time.fixedDeltaTime));
    		jump = false;
    	}
}

You should debug your code (either through logs or breakpoints), but what I would assume is happening is that for several frames your grounded check is still true and thus the AddForce is being called several times.

The code you have is an okay starting point and one solution would be to implement something like a “minimum jump timer”, which kicks off a timer and manages a “canJump” bool for you. This will need to be tweaked until it feels right with your grounded check, but something like this would work.

//Duration is a public class variable you pass in
private IEnumerator DisableJump(float duration)
{
      float timer = duration;
      canJump = false;

      while(timer > 0.0f)
     {
           timer -= time.deltaTime;
           yield return null; 
     }

     canJump = true; 
}

You would then call this using:

StartCoroutine(DisableJump(jumpTimer));

Lastly, you would want to remove the setting of the jump bool from the update logic and check to make sure you can jump, something like this:

function Update()
{
      if(Input.GetMouseButton(0))
      {
             if(grounded && canJump)
             {
                   myRigidbody.AddForce(new Vector2(0, 1500f * Time.fixedDeltaTime));;            
                  StartCoroutine(DisableJump(jumpTimer));       
             }    
       }
}

Unity also has a free character controller, and there are several others you can find out there for free, where they tackle similar issues. Looking at how they handle grounded checks and jump logic would be a good training exercise and something I would advise if you have the time for it.