Last active
January 21, 2021 09:33
-
-
Save thebne/370c2bfbb89134403f4cd0462768b194 to your computer and use it in GitHub Desktop.
Get closest point on bounds (not within)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Vector3 GetClosestPointOnBounds(Bounds bounds, Vector3 point) | |
{ | |
var boundPoint1 = bounds.min; | |
var boundPoint2 = bounds.max; | |
var points = new Vector3[] { | |
new Vector3(boundPoint1.x, boundPoint1.y), | |
new Vector3(boundPoint1.x, boundPoint2.y), | |
new Vector3(boundPoint2.x, boundPoint2.y), | |
new Vector3(boundPoint2.x, boundPoint1.y), | |
}; | |
return new Vector3[] | |
{ | |
GetClosestPoint(point, points[0], points[1]), | |
GetClosestPoint(point, points[1], points[2]), | |
GetClosestPoint(point, points[2], points[3]), | |
GetClosestPoint(point, points[3], points[0]), | |
}.OrderBy(l => l.sqrMagnitude).First(); | |
} | |
Vector3 GetClosestPoint(Vector3 point, Vector3 line_start, Vector3 line_end) | |
{ | |
Vector3 line_direction = line_end - line_start; | |
float line_length = line_direction.magnitude; | |
line_direction.Normalize(); | |
float project_length = Mathf.Clamp(Vector3.Dot(point - line_start, line_direction), 0f, line_length); | |
return line_start + line_direction * project_length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment