Do not use OnTriggerStay
to do this. That’s not guaranteed to be true very time.
Set isGrounded flag to true when OnCollisionEnter
is called. Set it to false when OnCollisionExit
is called.
bool isGrounded = true;
private float jumpForce = 2f;
private Rigidbody pRigidBody;
void Start()
{
pRigidBody = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
pRigidBody.AddForce(new Vector3(0, jumpForce, 0));
}
}
void OnCollisionEnter(Collision collision)
{
Debug.Log("Entered");
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
void OnCollisionExit(Collision collision)
{
Debug.Log("Exited");
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}
Before you say it doesn’t work, please check the following:
-
You must have
Rigidbody
orRigidbody2D
attached to the player. -
If this
Rigidbody2D
, you must useOnCollisionEnter2D
and
OnCollisionExit2D
. -
You must have Collider attached to the player with IsTrigger
disabled. -
Make sure you are not moving the
Rigidbody
with the transform such
astransform.position
andtransform.Translate
. You must move
Rigidbody
with theMovePosition
function.