Reputation: 361
I've looked through some of the other close answers here but can't find any solutions to my problem.
I have a polygon that is rotated around an axis position, and I need to find the bounding box of the polygon. Essentially, the bounding box object should have the x
and y
position of the top left corner, and the width
and height
of the box itself. I am able to calculate the box of the polygon without rotation using this code, but it doesn't account for rotation too. The red square is the current bounding box without rotation, the green circle is the rotation axis, and the polygon is the polygon itself.
Ideally, I don't want to re-compute each vertex position on each call to get the bounding box, I want it to be in the math itself. Here's an example of the polygon and the bounding box without rotation: https://i.imgur.com/MSOM9Q1.mp4
Here is my current code for finding bounding box for the non-rotated polygon:
const minX = Math.min(...this.vertices.map((vertex) => vertex.x));
const minY = Math.min(...this.vertices.map((vertex) => vertex.y));
return {
x: minX + this.position.x,
y: minY + this.position.y,
width: Math.max(...this.vertices.map((vertex) => vertex.x)) - minX,
height: Math.max(...this.vertices.map((vertex) => vertex.y)) - minY
};
Polygon object structure:
position
is the center of the polygonrotationAxis
is a vector relative to the center of the polygon (position)vertices
array is a list of vectors relative to the center of the polygonBounding box structure:
What do I need to do calculate the bounding box of the rotated polygon?
Upvotes: 1
Views: 812
Reputation: 51835
if you do not want to recompute the axis aligned BBOX from all the vertexes of polygon after any rotation/translation then do it from OBB that is only 4 vertexes ...
Compute OBB of unrotated/untranslated polygon
this operation is slow but its done just once (unless your polygon is changing shape or size)
At any transformation of polygon
transform the OBB vertexes in the same way too. And then compute axis aligned BBOX from transformed OBB vertexes (just finding min/max coordinates as you do now).
This way you have to compute stuff from only 4 vertexes instead of N
transforming the complexity from O(N)
into O(1)
.
Also having OBB might come in handy later on as it can speed up some operation or even improve precision of collision testing etc ...
Upvotes: 2