counter doesnt increment in update with unity

384 views Asked by At

I have a simple code that makes my character jump,

My character can jump as long as he's current jump is lower than the maxNumber of jumps.

and every time he jumps i add 1 to his current jump.

my problem is the jump counter doesnt always add one? even when the character jumps, he jumps with no problems but the counter doesnt always respond.

he is allowed to jump twice, but from time to time the player does hes first jump without anything being added to his current jump.

 // Jumping
public int maxNoJumps = 2;
public int currentJumpNo = 0;
public bool canPlayerJump = false;
public float JumpVelocity = 25;

 void Update () 
 {

grounded = Physics2D.Linecast (transform.position, groundCheck.position, 1 << LayerMask.NameToLayer ("Ground"));

  if (grounded)
  {
   currentJumpNo = 0;
  }

 // SETTING IF PLAYER IS ABLE TO JUMP
 if (currentJumpNo < maxNoJumps) 
 {
     canPlayerJump = true;
 } else 
 {
     canPlayerJump = false;
 }


 // IF PLAYER PRESSES SPACE AND IS ABLE TO JUMP
 if (Input.GetKeyDown (KeyCode.Space) && canPlayerJump) 
 {
     currentJumpNo+=1;
     rb2d.velocity = new Vector2 (rb2d.velocity.x, JumpVelocity);

 }
}

like i said the player jumps even when the counter doesnt go up allowing him sometimes to jump 3 times.

also i have tried it in fixed update and it's still the same and incrementing in different ways.

thank in advance for helping

1

There are 1 answers

3
Joseph Cooper On

I would suggest keeping your jumps seperate and using booleans instead.

For instance instead of

if (currentJumpNo < maxNoJumps) 
 {
     canPlayerJump = true;
 } else 
{
    canPlayerJump = false;
}

use:

if (grounded) 
 {
     canPlayerJump = true;
     doubleJump = true;
 } else if(doubleJump)
{
    canPlayerJump = true;
}
else
{
canPlayerJump = false;
}

and then in your jump section

if (Input.GetKeyDown (KeyCode.Space) && canPlayerJump) 
  {
     doubleJump = (grounded)? true:false;
     rb2d.velocity = new Vector2 (rb2d.velocity.x, JumpVelocity);

 }

this basically says if they are grounded before they jump they still have double jump. If they are not grounded they lose the double jump.

I hope very much that this will help you in your project. If the problem persists, just reply and I will see if I can create an alternate jump function that should work as well.