Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

perpendicular line to collision surface

Discussion in 'Scripting' started by YOLOnerds, Mar 19, 2022.

  1. YOLOnerds

    YOLOnerds

    Joined:
    Jan 20, 2017
    Posts:
    4
    I am trying to get a perpendicular line to the surface of an object the character collides with, however it looks like the collision normal is relative to the origin (always within 1 unit of the origin) so I cannot draw a line from collision point to the normal and expect a perpendicular line to the collision surface. Is that a normal behavior (no pun intended)?

    I was able to get a perpendicular line to the surface of the object by adding the position of the object to the normal to get a "corrected" normal value and then draw the line from object's origin to the new normal vector. I have a feeling that this isn't a correct approach. Thoughts?

    Blue lines are generated with the code below while the red line is a raycast from the collision point directly to the original normal.

    normals.PNG

    Blue Lines

    Code (CSharp):
    1.  
    2.     void OnControllerColliderHit(ControllerColliderHit hit)
    3.    {
    4.        var point = hit.point;
    5.        var dir = -hit.normal;
    6.        // step back a bit
    7.        point -= dir;
    8.        RaycastHit hitInfo;
    9.        // cast a ray twice as far as your step back. This seems to work in all
    10.        // situations, at least when speeds are not ridiculously big
    11.        if (hit.collider.Raycast(new Ray(point, dir), out hitInfo, 2))
    12.        {
    13.             var normal = hitInfo.normal;
    14.  
    15.             Debug.DrawLine(hit.transform.position, hit.transform.position + hitInfo.normal, Color.blue, 100f);
    16.         }
    17.    }
    18.  
    Red Line

    Code (CSharp):
    1.  
    2. Debug.DrawLine(forwardHitInfoTop.point, forwardHitInfoTop.normal, Color.red);
    3.  
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    The collision normal is a normalized direction vector. yes it is expected that the magnitude of that vector is always 1, as it is intended to convey a direction only.
    Sure you can:
    Code (CSharp):
    1. Debug.DrawLine(hitInfo.point, hitInfo.point + hitInfo.normal, Color.green);
     
  3. YOLOnerds

    YOLOnerds

    Joined:
    Jan 20, 2017
    Posts:
    4
    that worked, thanks!