I want the player to jump when the player is grounded.
private void OnTriggerStay(Collider other)
{
if(other.gameObject.layer == 8)
{
isGroun
Use this to check if collision is detected at all, it's good starting point for further debuging:
private void OnTriggerStay(Collider other)
{
Debug.Log(other);
}
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
or Rigidbody2D
attached to the player.
If this Rigidbody2D
, you must use OnCollisionEnter2D
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
as transform.position
and transform.Translate
. You must move
Rigidbody
with the MovePosition function.