Search Unity

Best way to determine which "face" was hit for a box collider

Discussion in 'Scripting' started by Lypheus, Nov 28, 2012.

  1. Lypheus

    Lypheus

    Joined:
    Apr 16, 2010
    Posts:
    664
    I'm writing some code where a player interacts with a given object (in this case a fence to vault over) and want to determine if my raycast is hitting the front/back of it or the sides/top.

    Currently this is my attempt:

    Code (csharp):
    1.  
    2.     public static bool IsFrontOrBack( Collider collider, Vector3 hit )
    3.     {
    4.         Vector3 localHit = collider.transform.InverseTransformPoint( hit );
    5.         return Mathf.Abs( localHit.z ) >= collider.bounds.size.z / 2.0f;
    6.     }
    7.  
    It appears to work but is certainly less than ideal - for one it is possible (if unlikely) that you could see a high enough z value using a raycast from the side (furthest corners). Is this as good as it gets or does anyone have something cleaner kicking around?
     
  2. MicroEyes

    MicroEyes

    Joined:
    Jul 3, 2012
    Posts:
    309
    Use
    Code (csharp):
    1. ContactPoint.point
    in OnCollisionEnter, OnCollisionStay OR OnCollisionExit
     
  3. Lypheus

    Lypheus

    Joined:
    Apr 16, 2010
    Posts:
    664
    This is a ray cast use case so no collisions unfortunately.