Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm making a platform sidescrolling game. All I want to do is to detect if my character is on the floor:

function OnCollisionStay (col : Collision){
    if(col.gameObject.tag == "Floor"){
        onFloor = true;
    } else {onFloor = false;}
}
function OnCollisionExit (col : Collision){
    onFloor = false;
}

But I know this isn't the accurate way. If I hit a cube with a "floor" tag, in the air (no matter if with the character's feet or head) I would be able to jump.

Is there a way to use the same box collision to detect if I'm touching something from a specific side?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

You don't have to have only one collider on your character; you can have multiple colliders to perform different checks!

I would suggest creating a separate collider that is located on your character's feet. You could also have a collider for the top of your head, or maybe your front or back so you know when you bump into a wall...

Another way would be, when you collide with something, use Physics.Raycast or Physics.RaycastAll to check for points just below your feet, to see if you're standing on ground or not.

If you really wanted to only use one collider, within your collision functions, you could check the col.contacts points to see if the collision occurred above or below the mid point of your collider.

share|improve this answer
    
If I'm willing to use more than one box collider component, how do I identify each one within the same game object? –  Fabián Jun 2 at 6:24
    
Set them up as vars in your class, like var headCol:BoxCollider; var feetCol:BoxCollider;, then in the Unity editor, drag each BoxCollider component into their respective var slot. –  Chris Jun 2 at 8:33

You can check the col.normal, well that's how I do this. For example if the x value is 1, I know the collision is on the bottom of my collider. (that's an example, I don't recall the values of the normals)

share|improve this answer
1  
You could try to be more specific for your future answers. It could be good to add some details. –  Heckel Jun 2 at 10:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.