public static IntersectPoints ClosestPointsOnSegmentToLine(Vector3 segment0, Vector3 segment1, Vector3 linePoint, Vector3 lineDirection) { IntersectPoints closests = ClosestPointsOnTwoLines(segment0, segment1 - segment0, linePoint, lineDirection); closests.First = ClampToSegment(closests.First, segment0, segment1); return(closests); }
float ClosestDistanceFromMouseToLines(List <Vector3> lines) { Ray mouseRay = myCamera.ScreenPointToRay(Input.mousePosition); float closestDistance = float.MaxValue; for (int i = 0; i < lines.Count; i += 2) { IntersectPoints points = Geometry.ClosestPointsOnSegmentToLine(lines[i], lines[i + 1], mouseRay.origin, mouseRay.direction); float distance = Vector3.Distance(points.first, points.second); if (distance < closestDistance) { closestDistance = distance; } } return(closestDistance); }
//Returns 2 points since on line 1 there will be a closest point to line 2, and on line 2 there will be a closest point to line 1. public static IntersectPoints ClosestPointsOnTwoLines(Vector3 point1, Vector3 point1Direction, Vector3 point2, Vector3 point2Direction) { IntersectPoints intersections = new IntersectPoints(); //I dont think we need to normalize //point1Direction.Normalize(); //point2Direction.Normalize(); float a = Vector3.Dot(point1Direction, point1Direction); float b = Vector3.Dot(point1Direction, point2Direction); float e = Vector3.Dot(point2Direction, point2Direction); float d = a * e - b * b; //This is a check if parallel, howeverm since we are not normalizing the directions, it seems even if they are parallel they will not == 0 //so they will get past this point, but its seems to be alright since it seems to still give a correct point (although a point very fary away). //Also, if they are parallel and we dont normalize, the deciding point seems randomly choses on the lines, which while is still correct, //our ClosestPointsOnTwoLineSegments gets undesireable results when on corners. (for example when using it in our ClosestPointOnTriangleToLine). if (d != 0f) { Vector3 r = point1 - point2; float c = Vector3.Dot(point1Direction, r); float f = Vector3.Dot(point2Direction, r); float s = (b * f - c * e) / d; float t = (a * f - c * b) / d; intersections.First = point1 + point1Direction * s; intersections.Second = point2 + point2Direction * t; } else { //Lines are parallel, select any points next to eachother intersections.First = point1; intersections.Second = point2 + Vector3.Project(point1 - point2, point2Direction); } return(intersections); }