Reputation: 3
Ok so I'm building a platformer with two types of jump. Normal jump - whilst on ground, pressing space bar Air jump - whilst jumping, a limited amount of extra jumps (also whilst pressing space bar)
I've worked out the main mechanics for this jump, But I've hit a snag. the limited amount of airjumps starts as 3 each time you jump. However, with the code I've written, Unity is using the initial "normal jump" as one of the three.
Here is a sample of my code below:
bool pressingJumpButton = Input.GetKeyDown("space");
if (pressingJumpButton)
{
if (canJump)
{
jumping = true;
}
}
if (jumping)
{
if (pressingJumpButton && inAir == false) {
Debug.Log("jump");
GetComponent<Rigidbody>().velocity = new Vector3(
GetComponent<Rigidbody>().velocity.x,
jumpingSpeed,
GetComponent<Rigidbody>().velocity.z);
inAir = true;
}
}
//airJump logic
if(inAir==true)
{
airJump = true;
if (airJump && maxAir>0 && pressingJumpButton)
{
Debug.Log("airJump");
maxAir -= 1;
GetComponent<Rigidbody>().velocity = new Vector3(
GetComponent<Rigidbody>().velocity.x,
jumpingSpeed,
GetComponent<Rigidbody>().velocity.z);
}
}
// on the floor
void OnTriggerStay (Collider otherCollider)
{
if (otherCollider.tag =="JumpingArea")
{
canJump = true;
jumping = false;
inAir = false;
maxAir = 3;
airJump = false;
}
}
I put the debug.logs in to see if I could find the issue and when I'm doing the first jump (from the ground) its registering as both normal and air jumps.
I thought that by having an inAir bool that only returns true after pressing the jump button once would be the fix but no luck.
What am I doing wrong?
Upvotes: 0
Views: 164
Reputation: 3058
You need to combine your jumping and in air test and use an else
clause. As it's written, you are doing the jump, setting inAir = true
and then after that testing if inAir
is true, meaning you are always doing an air jump after every normal jump.
if (jumping && !inAir)
{
Debug.Log("jump");
...
}
else if (inAir && jumping)
{
Debug.Log("airJump");
...
}
There is also no need to recheck pressingJumpButton
since you've already tested that when setting jumping = true
.
A (IMHO) better version that avoids repeated code and gets rid of unnecessary variables:
if (pressingJumpButton && canJump)
{
if (!inAir)
{
Debug.Log("jump");
inAir = true;
DoJump();
}
else if (maxAir > 0)
{
Debug.Log("airJump");
maxAir--;
DoJump();
}
}
private void DoJump()
{
GetComponent<Rigidbody>().velocity =
new Vector3(GetComponent<Rigidbody>().velocity.x,
jumpingSpeed,
GetComponent<Rigidbody>().velocity.z);
}
Upvotes: 2