- Home /
How to check if object is on ground (C#)?
I am in the process of writing custom TPP movement script, using Rigid body (with restricted rotations) and capsule collider. However, in order for my character to jump correctly, I need to know if character is on ground. How can I check that, using capsule collider and rigidbody?
Answer by Piflik · Jan 05, 2013 at 07:04 PM
Use a boolean variable and control it via OnCollisionEnter/Exit/Stay.
Well, but how to do that exactly? I'd like to have it set on ground only if it is really on ground and not e.g. touching wall (don't want wall jumps).
Use a 'Ground' tag and only change the boolean if the object you collided with has this tag.
Piflik, in my game, about anything is ground (except things like enemies), so I don't want to add this tag to gazillion of objects, sorry - not gonna work.
@Lovrenc - the problem is that I don't know how to check if collision was on the bottom of my character - I know theory, did something like this in the past, with other engines, but don't know how to check if collision happened on the bottom of collider in Unity.
The CharacterController has collisionFlags that tell you where the collision happened (top, sides, bottom), but a Collider doesn't. You could possibly build something similar with the Collision.contacts[i].normal vectors.
$$anonymous$$aybe something like this:
public float threshold;
private bool isGrounded;
void OnTriggerEnter(Collision other) {
foreach(ContactPoint temp in other.contacts) {
if(Vector3.Cross(temp.normal, Vector3.up) < threshold) {
isGrounded = true;
}
}
}