Mike Coleman
Mike Coleman

Reputation: 3

Calculate Polygon Rotation so Right Angles are Straight

I have a polygon (RED SQUARE), for simplicity its a square 100x100 with an offset of 100 from the top left. Assume the coordinate system top left is 0,0. So the coordinates for my simple square are: [x:100,y:100],[x:100,y:200],[x:200,y:200], [x:200,y: 100].

Now lets say I have another square (BLUE SQUARE), its a 100x100 square also, with the same 100 offset from the top left, but this square is rotated 45 degrees, so its cords are: (rounded) [x:150,y:79],[x:79,y:150],[x:150,y:221],[x:221,y:150].

How do I calculate the rotation of BLUE SQUARE (45 degrees) if I am given only the coordinates? Assuming I want the right angles to be straight (vertical or horizontal) in this coordinate system (Like RED SQAURE).

Worded another way... Given these coordinates: [x:150,y:79],[x:79,y:150],[x:150,y:221],[x:221,y:150] how do I calculate the rotation to apply to polygon so its coordinates are this: [x:100,y:100],[x:100,y:200],[x:200,y:200], [x:200,y: 100]

Here is a image demonstrating what I am talking about. Image of both polygons with coordinates

Upvotes: 0

Views: 457

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35011

The way you do this is to

  1. calculate the angle between two adjacent points. The formula for this Math.atan2(x2-x1, y2-y1); This will give you the angle the quadrilateral is on.
  2. Rotate the quadrilateral (from its center) by -angle (or by pi/2 - angle) and one side will be horizontal and one will be vertical

Upvotes: 0

Related Questions