Using collision for jump in 3d

Hello!

I’m working on a jump script for a ball. I used OnCollisionStay with the intention of putting a restriction on jump so that you can’t just jump off of air and fly away into the sunset. It’s working great, except that collision isn’t detected unless the ball is moving, so you cannot jump from a stopped position. Any advice?

void OnCollisionStay(Collision collisionInfo)
{
if (Input.GetButtonDown(“Jump”))
{
rb.AddForce(0, JumpForce, 0, ForceMode.Impulse);
}

}
}

Thank you!

first of all, please use code tags.

what is usually done with jumping is keeping a bool called something like “canJump”, if it’s true you can jump and when you jump it’s set to false, when you land back on the ground (detected via OnCollisionEnter or something) it’s set back to true allowing the player to jump again.

you can also extend this to a double/triple/etc jump very easily.

look out for situations where the player gets airborne with out jumping, either disable the “canJump” bool or cross check with another function that checks for ground contact.

I’m not sure why it only works when the ball is moving - did you try debugging it?

One other problem you have is you’re looking for input in the fixed update loop, it’s okay when you’re reading from an axis that changes value over time or looking for GetButton/GetKey, but when you’re using the Up/Down versions you can miss the input because it cycles on the update loop and this call back is on the fixed update loop.

The most likely thing is the Rigidbody falling asleep. You can test this by printing the sleep (or isSleep or whatever it’s called) property out. You can also force it to stay awake.

1 Like