Search Unity

Check if Player is on Ground

Discussion in 'Getting Started' started by SansPapyrus683, Jun 16, 2022.

  1. SansPapyrus683

    SansPapyrus683

    Joined:
    May 8, 2020
    Posts:
    8
    So I'm making a simple platformer, and here's the code I have to check if the user is on the ground:
    Code (CSharp):
    1. private void OnCollisionEnter2D(Collision2D col)
    2. {
    3.     if (col.gameObject.CompareTag("Ground"))
    4.     {
    5.         _grounded = true;
    6.     }
    7. }
    The problem is, this can result in the user being able to wall jump along with them not being able to jump if they're on some dynamic moving object that isn't the ground (i.e. an enemy).
    I was thinking of attaching a second box collider to the bottom of the user and check when that collides with something, but apparently you can't have two colliders of the same type on an object.
    I was also thinking of constantly performing raycasts to see if the user is on the ground, but I fear that would be too expensive.

    How do I check if the user is on the ground using only colliders & the like?
     
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    I don't have the performance tests in front of me to back it up, but I have to imagine that doing a raycast from the bottom of the player straight down to determine if they're grounded or not is far less expensive than using the physics system.
     
  3. SansPapyrus683

    SansPapyrus683

    Joined:
    May 8, 2020
    Posts:
    8
    Actually, I managed to address the problem by making a child collider and having that send a signal to the main player when it hits the ground.
    Thanks for the help though!