简体   繁体   中英

Unity - Checking if the player is grounded not working

I want the player to jump when the player is grounded.

private void OnTriggerStay(Collider other)
{
    if(other.gameObject.layer == 8)
    {
        isGrounded = true;
    }else { isGrounded = false; }
}

The player is on air when spawning. After the player falls to the Terrain, which has the tag Ground , isGrounded is still false. When I set isGrounded manually true and jump again, it's still true after collision. I also don't want the player to double jump in the air, which I probaly already coded but is not working because something is wrong.

Changing OnTriggerStay to OnTriggerEnter doesn't change something. I hope you can help me.

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.

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);
}

You must have Collider attached to the player with IsTrigger disabled.

I think you mean enabled? I was struggling to get this to work but as soon as I enabled the collider's IsTrigger it started actually working. The OnTriggerEnter/Exit doesn't seem to do very much on a collider that isn't actually a trigger...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM