public Vector3 FindClosest(Vector3 point) { float currBestDist = Mathf.Infinity; Vector3 bestPoint = root.position; root.FindClosestRec(point, ref currBestDist, ref bestPoint, 0); return(bestPoint); }
public void FindClosestRec(Vector3 point, ref float currBestDist, ref Vector3 currBest, int axis) { float dist = (point - position).sqrMagnitude; if (dist < currBestDist) { currBestDist = dist; currBest = position; } float diff = point[axis] - position[axis]; bool leftFirst = diff <= 0; axis = (axis + 1) % 3; if (leftFirst) { if (left != null) { left.FindClosestRec(point, ref currBestDist, ref currBest, axis); } if (diff * diff < currBestDist && right != null) { right.FindClosestRec(point, ref currBestDist, ref currBest, axis); } } else { if (right != null) { right.FindClosestRec(point, ref currBestDist, ref currBest, axis); } if (diff * diff < currBestDist && left != null) { left.FindClosestRec(point, ref currBestDist, ref currBest, axis); } } }