Reputation: 53
I'm trying to make my character be able to jump whenever he is grounded OR if he's airborne to only be able to jump when he has extra jumps and x amount of time has passed. Currenty I have this:´
void Jump()
{
jumpTime -= Time.fixedDeltaTime;
if ((jumpRemember > 0) && ((groundRemember > 0) || ((jumps>0) && (jumpTime <= 0))))
{
jumpRemember = 0;
groundRemember = 0;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumps--;
jumpTime = timeSinceLastJump;
}
}
(the jump remember and ground remember are checks to see if i pressed the jump button or was grounded in the last 0.1 seconds)
but when he is grounded and collides with a roof and get sent back to ground he cant jump after the time has passed anyways, even though I used the ''OR'' operator.
Upvotes: 4
Views: 89
Reputation: 841
I think you have misplaced parenthesis. You want both of the first two true or both of the second two right?
if ((jumpRemember > 0) && ((groundRemember > 0) || ((jumps>0) && (jumpTime <= 0))))
should it be?
if ((jumpRemember > 0 && groundRemember > 0) || (jumps>0 && jumpTime <= 0))
That second parenthesis in front of groundRemember is causing it to be grouped with the two to the right of the or statement. You are requiring remember all the time and then either ground remember > 0 OR the other two to both be true. It doesn't sound like that is what you are intending. Is it?
Upvotes: 1
Reputation: 5108
An example how you could approach your issue.
const int MAX_JUMPS = 2;
const FLOAT JUMP_TIMER = 1;
const float JUMP_FORCE = 100;
int jumps = 2;
float nextJump = 0;
bool grounded = true;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
TryJump();
}
void TryJump()
{
if (grounded || (jumps > 0 && nextJump < Time.time))
{
Jump();
}
}
void Jump()
{
rb.velocity = new Vector2(rb.velocity.x, JUMP_FORCE);
jumps--;
nextJump = Time.time + JUMP_TIMER;
}
void Grounded()
{
grounded = true;
jumps = MAX_JUMPS;
}
void Airborne()
{
grounded = false;
}
void OnCollisionEnter(Collision col)
{
if (col.tag == "Floor")
Grounded();
}
void OnCollisionExit(Collision col)
{
if (col.tag == "Floor")
Airborne();
}
Upvotes: 2
Reputation: 378
Try using Debug.Log(variable) to check the states of your variables.
"when he is grounded and collides with a roof and get sent back to ground" - What variables does this change?
Are any of these variables being changed unexpectedly when the character collides with the roof?
I would leave this in a comment but you need reputation to unlock that feature of this site.
Upvotes: 3