If the Y axis is your vertical direction (most frequent case), you can check normal.y: positive values mean collision with the bottom side, and negative values mean top collisions:
function OnCollisionEnter ( other : Collision ) {
if ( other.gameObject.CompareTag ( "Floor" ) ) {
var normal = other.contacts[0].normal;
if (normal.y > 0) { //if the bottom side hit something
Debug.Log ("You Hit the floor");
}
if (normal.y < 0) { //if the top side hit something
Debug.Log ("You Hit the roof");
}
}
}
normal.y is numerically equal to the sine of the normal angle relative to the horizontal plane, thus you can refine your code by accepting floor or roof collisions only when the normal.y is higher than the sine of the angle ( < -45 or > 45, for instance, would become normal.y < -0.707 or normal.y > 0.707).
But be aware that OnCollisionEnter is only reported when a rigidbody hits a collider; if your character is a CharacterController, you must use OnControllerColliderHit instead:
function OnControllerColliderHit ( hit : ControllerColliderHit ) {
if ( hit.gameObject.CompareTag ( "Floor" ) ) {
var normal = hit.normal;
if (normal.y > 0) { // if the bottom side hit something
Debug.Log ("You Hit the floor");
}
if (normal.y < 0) { // if the top side hit something
Debug.Log ("You Hit the roof");
}
}
}
NOTE: This event is sent all the time due to the contact of the character with the ground, thus you will get lots of “You hit the floor” messages.