Unity - Checking if the player is grounded not working

前端 未结 2 1630
我寻月下人不归
我寻月下人不归 2020-11-27 22:28

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

private void OnTriggerStay(Collider other)
{
    if(other.gameObject.layer == 8)
    {
        isGroun         


        
相关标签:
2条回答
  • 2020-11-27 23:00

    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);
    }
    
    0 讨论(0)
  • 2020-11-27 23:27

    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.

    0 讨论(0)
提交回复
热议问题