Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Mathfx Update

Discussion in 'Scripting' started by mjjw, Sep 22, 2006.

  1. mjjw

    mjjw

    Joined:
    Nov 12, 2005
    Posts:
    59
    Not sure if it was the right place to put it, but I have added a function to Mathfx on the Wiki to determine the closest point on a line to a point.

    There is a slight danger of division by zero, but I'll leave it to the individual to cope with that!

    Anyway, the function is:
    Code (csharp):
    1.  
    2.     public static Vector3 NearestPoint(Vector3 lineStart, Vector3 lineEnd, Vector3 point)
    3.     {
    4.         Vector3 lineDirection = Vector3.Normalize(lineEnd-lineStart);
    5.         float closestPoint = Vector3.Dot((point-lineStart),lineDirection)/Vector3.Dot(lineDirection,lineDirection);
    6.         return lineStart+(closestPoint*lineDirection);
    7.     }
    8.  
    Suggestions appreciated if anyone has a more efficient way of doing this?