Search Unity

Question How to get closest point on (finite) line in ShaderGraph?

Discussion in 'Shader Graph' started by Stacklucker, Apr 11, 2021.

  1. Stacklucker

    Stacklucker

    Joined:
    Jan 23, 2015
    Posts:
    82
    Is is possible to calculate the closest point on a line given a point p in 3d space in shadergraph?

    For reference, this is one way to do the calculations in code:

    Code (CSharp):
    1.  
    2. // For finite lines:
    3. Vector3 GetClosestPointOnFiniteLine(Vector3 point, Vector3 line_start, Vector3 line_end)
    4. {
    5.     Vector3 line_direction = line_end - line_start;
    6.     float line_length = line_direction.magnitude;
    7.     line_direction.Normalize();
    8.     float project_length = Mathf.Clamp(Vector3.Dot(point - line_start, line_direction), 0f, line_length);
    9.     return line_start + line_direction * project_length;
    10. }
    11.  
    12. // For infinite lines:
    13. Vector3 GetClosestPointOnInfiniteLine(Vector3 point, Vector3 line_start, Vector3 line_end)
    14. {
    15.     return line_start + Vector3.Project(point - line_start, line_end - line_start);
    16. }
    Why do I want to do this? I am trying to get the distance between a vertex and the closest point on a line drawn from the main camera to the player character position. Then, based on the magnitude of that distance, I want to apply a dither transparency effect so that any object (with the specified shader) between the camera and player character becomes semi see through which allows you to see the player character at all times.
    Feel free to tell me if my approach is wrong.