2
votes

I'm working on a Unity game where the player shoots on cubes to change their weight (it can be positive or negative, last one meaning 'falling' to the roof) and i'm experiencing a problem with rigidbodies, spherecasting and detecting if the player is grounded or not.

When my player is on the ground or on top of any object with a collider, I detect it as 'grounded' using the following function:

if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo, 
    ((m_Capsule.height / 2f) - m_Capsule.radius) + advancedSettings.groundRoofCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
    {
        m_IsGrounded = true;
    }

where advancedSettings.groundRoofCheckDistance is set to 0.01f.

Until there, everything works fine. But now, when I try to get on top of a cube with a non-kinematic rigidbody, I can't get that boolean to be true.

Here are two captures to illustrate my problem :

In this one, the player is falling on a non-kinematic rigidbody box and the boolean circled in red is m_isGrounded (false):

enter image description here

And here, same but the cube is kinematic and the ground is detected just fine:

enter image description here

I really can't figure out why the rigidbodies do that, or if I have a problem with my ground detection function, so any help is welcome. Thanks!

PS: I'm using Unity 2018.2.15f1

1

1 Answers

1
votes

There are many ways to detect if player is grounded or not. If raycast, SphereCast and other ray based detection API are not working properly, try something different. Use the callback functions such as OnCollisionEnter and OnCollisionExit with flag. Check that flag in the Update function.

bool m_IsGrounded;

void OnCollisionEnter(Collision collision)
{
    if (collision.collider.CompareTag("Ground"))
        m_IsGrounded = true;
}

void OnCollisionExit(Collision collision)
{
    if (collision.collider.CompareTag("Ground"))
        m_IsGrounded = false;
}

void Update()
{
    if (m_IsGrounded)
    {
        Debug.Log("Grounded");
    }
}

Note that this is checking for the "Ground" tag so your ground object must be on the "Ground" tag. You have to manually create this tag from the Editor then change your ground object tag to this.