Search Unity

Ground checking

Discussion in 'Scripting' started by Nanako, Nov 21, 2014.

  1. Nanako

    Nanako

    Joined:
    Sep 24, 2014
    Posts:
    1,047
    I need some thoughts/concept ideas on how to check if a character is standing on the "ground". Although here, i define ground as basically any object they can come to rest on, that is capable of resisting gravity. not just terrain.

    I did a bit of searching and the first method i found is sending a raycast downwards to see if there's anything solid underneath you. However, i have a problem with this method;

    • With an extremely tight raycast (half of the collider's height plus minimum penetration depth plus 0.001 units) it detects collisions perfectly on flat surfaces, however it causes issues on rough terrain, and anything else that isn't perfectly flat
    • with a more loose raycast (a couple of units down) it works well on terrain of varying bumpiness, but it causes problems with jumping. The character reads as being onGround for a few frames after they leave the ground, and a few before they land. This mainly caused a lot of animation issues.
    I don't think there's any optimal length i can find between them. Which leaves the only other option i see, to do two raycasts per frame (at least while in midair)

    Does anyone have an alternative idea?
     
  2. drewradley

    drewradley

    Joined:
    Sep 22, 2010
    Posts:
    3,063
    Does it have a character controller component? If so, you can use "if (controller.isGrounded)".
     
  3. Stoven

    Stoven

    Joined:
    Jul 28, 2014
    Posts:
    171
    If your character has a rigidbody and collider (such as Mesh collider or other primitives that approximate their shape) and moves with physics, you can just use OnCollisionEnter and/or OnCollisionStay on a Monobehaviour attached to the character to determine if the character is grounded.

    You'll likely have to make some adjustments to your character's weight to make sure they are firmly grounded as you move, as to not accidentally trigger OnCollisionExit in case you want to set a boolean that updates your character's grounded status.
     
  4. Nanako

    Nanako

    Joined:
    Sep 24, 2014
    Posts:
    1,047
    nope, i'm not using that system.

    any idea how it's calculated internally?
     
  5. sootie8

    sootie8

    Joined:
    Mar 25, 2014
    Posts:
    233
    @Nanako I would use a combination of a downward raycast, and a check on the characters current velocity. If you use a rigidbody it is easy to get the current velocity, otherwise you will need to calculate it yourself.

    So you know its grounded, if your raycast calculation says its grounded & the velocity in Y axis is 0 (although you may need to play around with this value).