CodeHard_or_HardCode - 2 months ago 30

Python Question

Is it possible to write a function in python that could rotate any 2d structure with the arguments being only the coordinates (x,y) of the points in the structure? Additional arguments would be included for axis, speed and direction.

To my understanding it would only be possible by calculating point distance from symmetrical points and the axis and therefore it would always vary and is thus impossible except for 2d structures made up of standard shapes (triangles, rectangles, squares etc)

Good examples would be appreciated.

Answer

I have written such a function to use in pygame before. It is kinda self-explanatory but feel free to ask the parts that require clarification. Here is my code:

```
import math
def rotatePolygon(polygon,theta):
"""Rotates the given polygon which consists of corners represented as (x,y),
around the ORIGIN, clock-wise, theta degrees"""
theta = math.radians(theta)
rotatedPolygon = []
for corner in polygon :
rotatedPolygon.append(( corner[0]*math.cos(theta)-corner[1]*math.sin(theta) , corner[0]*math.sin(theta)+corner[1]*math.cos(theta)) )
return rotatedPolygon
my_polygon = [(0,0),(1,0),(0,1)]
print rotatePolygon(my_polygon,90)
```

This prints:

`[(0.0, 0.0), (6.123233995736766e-17, 1.0), (-1.0, 6.123233995736766e-17)]`

Which is nearly `[(0,0),(0,1),(-1,0)]`

I also have a function that rotates the given point(x,y) around another one. I share it in case you find it useful (And you can combine these two functions to rotate the polygon around another point rather than the origin):

```
def rotatePoint(centerPoint,point,angle):
"""Rotates a point around another centerPoint. Angle is in degrees.
Rotation is counter-clockwise"""
angle = math.radians(angle)
temp_point = point[0]-centerPoint[0] , point[1]-centerPoint[1]
temp_point = ( temp_point[0]*math.cos(angle)-temp_point[1]*math.sin(angle) , temp_point[0]*math.sin(angle)+temp_point[1]*math.cos(angle))
temp_point = temp_point[0]+centerPoint[0] , temp_point[1]+centerPoint[1]
return temp_point
print rotatePoint((1,1),(2,2),45)
```

This will print `(1.0, 2.414213562373095)`

,which is equal to `(1,1+sqrt(2))`

(Note that this one is **counter-clockwise**)