nearestPoint method
Returns a point on the shape's boundary which is closest to the given
point
.
The point
must lie outside of the shape. If there are multiple nearest
points, any one can be returned.
This method will not modify point
. At the same time, the caller does
not get ownership of the returned object: they must treat it as an
immutable short-lived object.
Implementation
@override
Vector2 nearestPoint(Vector2 point) {
var shortestDistance2 = double.infinity;
for (var i = 0; i < _vertices.length; i++) {
final vertex = _vertices[i];
final edge = _edges[i];
final dotProduct =
(point.x - vertex.x) * edge.x + (point.y - vertex.y) * edge.y;
final t = (dotProduct / edge.length2).clamp(-1.0, 0.0);
final edgePointX = vertex.x + edge.x * t;
final edgePointY = vertex.y + edge.y * t;
final dx = edgePointX - point.x;
final dy = edgePointY - point.y;
final distance2 = dx * dx + dy * dy;
if (distance2 < shortestDistance2) {
shortestDistance2 = distance2;
_tmpResult.setValues(edgePointX, edgePointY);
}
}
return _tmpResult;
}