# How do I ground my character using capsule colliders?

I have a problem checking if my character is grounded, and it is tied to the position of the capsule collider. I just started using Unity, so I'm not sure what I did wrong. The problem is that the Physics.SphereCast returns false, like it didn't hit anything.

When I start with the default CapsuleCollider, it seems to work, but my character floats in the air. I only have to lift it's y-position by 0.1, and it stops working. This is demonstrated, in the below image, but you can see this in more detail Here.

Here is the code showing how I detect if I'm grounded. Keep in mind that I'm working with a RigidBody, and not a CharacterController.

  bool IsGrounded()
{
Vector3 p1 = transform.position;
float distanceToObstacle = 0;
RaycastHit hit;
Collider collider = GetComponent<Collider>();

// Cast a sphere wrapping "controller" 0.1 meter down to check if it hits anything
if (Physics.SphereCast(p1,  collider.bounds.size.x / 2, new Vector3(0,-10,0), out hit))
{
distanceToObstacle = hit.distance;
if (distanceToObstacle < 0.1f)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}


## 1 Answer

You could always try using the onCollisionmethods that Unity has already (You may also want to play around with rigidbodies). Look into their Physics stuff because it offers collision and grounding already, , all you would have to do is play with sizes, numbers and so on. https://docs.unity3d.com/ScriptReference/Collision.html

As for your code in particular, make sure that your character doesn't have some sort of mesh or something (maybe set to invisible) around them that is actually the location your detection is starting at. So basically if he has a box around him that's 50cm, then your check for what's just underneath him may be working, it just might be starting at the bottom of that box.

• If we look at the documentation for Physics.SphereCast, we can see that p1 is being passed in as "The center of the sphere at the start of the sweep." This means that additional mesh around the player will have no effect on the position. This does mean that we need to provide world coordinates; if the collider is on a game object that is a child to any other game object, we will need to convert transform.position to world coordinates with transform.TransformPoint. Jan 26 '17 at 1:20
• @Gnemlock , first of all thank you for taking the time to rephrase my question! I don't quite understand how that should change depending on where the capsuleCollider is positioned in relation to the parent(the character)? Jan 26 '17 at 7:57
• @Gnemlock is saying that you need to change how you are using transform if the game object is a child to some other game object. Jan 26 '17 at 13:54
• I would recommend maybe not using a capsule collider just strapped onto his feet and try adding a collider to the character as a whole, which then you can just check when that collider touches the ground. Jan 26 '17 at 13:56