I'm trying to find the outermost vertices of a convex polygon (with relation to a point P outside the polygon). For now, I'm only concerned with rectangles (however, I'd like an algorithm that works with any convex polygon).
My plan is to construct a line from external point P to central point C. From this line of reference, I will construct lines from point P to points 1, 2, 3 and 4. Since points 2 and 4 will have the largest (most positive) and smallest (most negative) angles from the line of reference, they will be identified as the outermost vertices.
Is this the best algorithm for the job? How does one calculate angles from a reference angle (preferably in Java)?
I've drawn the lines (line of reference in red). As you can see, the line from P to 2 creates the largest angle on one side of the line of reference, while the line from P to 4 creates the largest angle of the other side. Hence, these are the outermost vertices.
I solved the problem as follows:
// code simplified for demonstration
double angleBetweenVertices;
double maxAngleBetweenVertices;
vectorA.setStartingPoint(outerPoint);
vectorA.setTerminationPoint(polygonCenter);
vectorB.setStartingPoint(outerPount);
// For each vertex, calculate the angle between the outer point, the polygon's center and the vertex
for (Point2D.Double vertex : vertices) {
vectorB.setTerminationPoint(vertex);
double angleBetweenVertices =
Math.toDegrees(
Math.atan2(
(vectorA.perpDotProduct(vectorB)),
(vectorA.dotProduct(vectorB))
)
);
// Update the min and Max
if (angleBetweenVertices >= maxAngleBetweenVertices) {
maxVertex = vertex;
maxAngleBetweenVertices = angleBetweenVertices;
} else if (angleBetweenVertices <= minAngleBetweenVertices) {
minVertex = vertex;
minAngleBetweenVertices = angleBetweenVertices;
}
}