I need to calculate the next position of the shape (X and Y) but don’t have any idea how. I tried different solutions but all-time something went wrong. Maybe someone can help me, I need a tip how it calculates, for best understand I will add screenshots.
Description: I have the image of the map in the background. I drew the shape on the image. After that, I need to rotate the background to N degrees (N can be from 0 to 360) and recalculate new position for shape (X, Y)
Parameters which I have:
- The start position of shape X and Y
- N degrees value
- Width and height of the shape
Also, I have the width and height of the background (if it will be needed).
Start position
Rotated the background to 90 degrees
Rotated the background to 90 degrees. Manually changed position of the shape X and Y can have some mistake
I need some algorithm to calculate a new position for shape, thanks for any help.
Advertisement
Answer
So you have rotated the background around its centre C about an angle of θ. You want to apply the same rotation to the shape’s point P.
A rotation of P about the origin can be achieved with:
P ′x = P x · cos θ
− P y · sin θ
P ′y = P x · sin θ
+ P y · cos θ
A rotation about a point C can be achieved by moving C to the origin, rotating, then moving C back. So:
P ′x
= (P x − C x) · cos θ
− (P y − C y) · sin θ
+ C x
P ′y
= (P x − C x) · sin θ
+ (P y − C y) · cos θ
+ C y
In JavaScript:
R.x = (P.x - C.x) * Math.cos(a) - (P.y - C.y) * Math.sin(a) + C.x R.y = (P.x - C.x) * Math.sin(a) + (P.y - C.y) * Math.cos(a) + C.y
where a is the sngle in radians. This will rotate clockwise. If you change the signs on the two sin terms, the rotation will be anticlockwise.
You can do the rotation on each of the points of your polygon or on the shape’s centre, in which case you must rotate the shape about its centre, too.