Home > other >  Unity collision with ground doesnt work (noob)
Unity collision with ground doesnt work (noob)

Time:03-29

So I just started working with unity and wanted that my player can only jump when he's touching the ground. I gave a "Ground" tag to my ground and checked, If the player is touching the gameObject with the "Ground" tag, so the grounded bool would be set to true. Somehow my collision doesnt work.

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] float speed = 10;
    private Rigidbody2D body;
    private Animator animate;
    private bool grounded;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
        animate = GetComponent<Animator>();
    }

    private void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

        if (horizontalInput > 0.01f)
            transform.localScale = new Vector3(7, 7, 7);

        else if (horizontalInput < -0.01f)
            transform.localScale = new Vector3(-7, 7, 7);

        if (Input.GetKeyDown(KeyCode.Space) && grounded == true)
            Jump();
              
            animate.SetBool("Run", horizontalInput != 0);
            animate.SetBool("grounded", grounded);
       

    }

    private void Jump()
    {
      body.velocity = new Vector2(body.velocity.x, speed);
        animate.SetTrigger("Jump");
        grounded = false;
    }

    private void OncollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Collision detected");
        if (collision.gameObject.tag == "Ground")
        grounded = true;
        Debug.Log("ground is being touched");
    }
    

}

I thought it would be a good idea to let certain steps of this process output a log message, but my log stayed empty after testing.

CodePudding user response:

OnCollisionEnter2D would be the right spelling of what you intented to write. So, change OncollisionEnter2D to OnCollisionEnter2D, because capitalization matters.

As we're already here and it won't harm, I'd also suggest you to use CompareTag instead of tag == string as it performs slightly better due to less memory allocation (as you can read here: https://learn.unity.com/tutorial/fixing-performance-problems#5c7f8528edbc2a002053b595), so it's a good habit to get used to CompareTag:

if(collision.gameObject.CompareTag("MyTag"))

To finish up this answer, I'd like to point out that you might want to consider fixing your auto-completion suggestions (in Visual Studio and Visual Studio Code: IntelliSense) in case it doesn't work. With the help of this tool, you'll never misspell something like this again, because the correct name will be suggested as soon as you start writing.

  • Related