First, we need a function to rotate a point around the beginning.
When we rotate the point (x, y) around the beginning in theta degrees, we get the coordinates:
(x * cos (theta) -y * sin (theta), x * sin (theta) + y * cos (theta))
If we want to rotate it around a point other than the origin, we just need to move it so that the center point becomes the origin. Now we can write the following function:
from math import sin, cos, radians def rotate_point(point, angle, center_point=(0, 0)): """Rotates a point around center_point(origin by default) Angle is in degrees. Rotation is counter-clockwise """ angle_rad = radians(angle % 360)
Some outputs:
print(rotate_point((1, 1), 90, (2, 1))) # This prints (2.0, 0.0) print(rotate_point((1, 1), -90, (2, 1))) # This prints (2.0, 2.0) print(rotate_point((2, 2), 45, (1, 1))) # This prints (1.0, 2.4142) which is equal to (1,1+sqrt(2))
Now we just need to rotate each corner of the polygon using our previous function:
def rotate_polygon(polygon, angle, center_point=(0, 0)): """Rotates the given polygon which consists of corners represented as (x,y) around center_point (origin by default) Rotation is counter-clockwise Angle is in degrees """ rotated_polygon = [] for corner in polygon: rotated_corner = rotate_point(corner, angle, center_point) rotated_polygon.append(rotated_corner) return rotated_polygon
Output Example:
my_polygon = [(0, 0), (1, 0), (0, 1)] print(rotate_polygon(my_polygon, 90))