Universal formula to calculate rotating by angle

1.1k Views Asked by At

I am generating roads and buildings that belong to them and since I want the streets to be rotated and then connected with each other, I need to rotate both them and their respective buildings. Is there a formula that would be able to translate (for example) my (x,y) point into point A given the (x,y) as the topleft corner of a building, (x1,y1) as the start of the street and alpha being the angle I am rotating by?

enter image description here

1

There are 1 best solutions below

2
On BEST ANSWER

Yes, there is:

First, typically in trig we assume $y$ increases when you go up on paper, but you have that flipped. But that's ok, since the angle is typically measured counter-clockwise, while your $\alpha$ is measured clock-wise, so the math will actually work out just the same.

That is, in general, if you have a point that is at $(x,y)$, when assuming the rotation point is the origin $(0,0)$, then if you rotate by $\alpha$ degrees, then the new point will be at $(x',y')$, where:

$$x'=x\cdot cos \ \alpha - y \cdot sin \ \alpha$$

$$y'=y\cdot cos \ \alpha + x \cdot sin \ \alpha$$

Now, applied to your case, since your point of rotation is not $(0,0)$, but is $(x1,y1)$, we first need to find the points relative to the rotation point $(x1,y1)$, so we need to shift the coordinate system by subtracting$1$ and $y1$. For example your original point $(x,y)$ would be considered at $(x,y)_S=(x-x1,y-y1)$, assuming $(x1,y1)$ is at $(0,0)$.

$$x_A=(x-x1)\cdot cos \ \alpha - (y-y1) \cdot sin \ \alpha$$

$$y_A=(y-y1)\cdot cos \ \alpha + (x-x1) \cdot sin \ \alpha$$

OK, but again this is relative to taking $(x1,y1)$ as the origin, so to get the $x$ and $y$ back relative to your coordinate system, we need to add $x1$ and $y1$ back, i.e. we get:

$$x_A=x1+(x-x1)\cdot cos \ \alpha - (y-y1) \cdot sin \ \alpha$$

$$y_A=y1+(y-y1)\cdot cos \ \alpha + (x-x1) \cdot sin \ \alpha$$

As another example, point $D$ ends up at:

$$x_D=x1+(x-x1)\cdot cos \ \alpha - (y+h-y1) \cdot sin \ \alpha$$

$$y_D=y1+(y+h-y1)\cdot cos \ \alpha + (x-x1) \cdot sin \ \alpha$$