Skip to content
Advertisement

Recalculation next position (x and y) based on rotate to N degree

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
    1

  • Rotated the background to 90 degrees
    2

  • Rotated the background to 90 degrees. Manually changed position of the shape X and Y can have some mistake
    3

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:

    Px = P x · cos θP y · sin θ
    Py = 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:

    Px = (P xC x) · cos θ − (P yC y) · sin θ + C x
    Py = (P xC x) · sin θ + (P yC 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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement