I have a line with lenght of l and p1 and p2 and i want to rotate it by angle. I was using this matrix but it doesn’t work.
I have this code in python:
JavaScript
x
9
1
def rotate (point, point2, angel):
2
x1 = (cos(radians(angel)) * point1.x) +( sin(radians(angel)) * point1.y)
3
y1 = (-1 * sin(radians(angel)) * point1.x )+ (cos(radians(angel)) * point1.y)
4
5
x2 = (cos(radians(angel)) * point2.x) + (sin(radians(angel)) * point2.y)
6
y2 = (-1 * sin(radians(angel)) * point2.x) + (cos(radians(angel)) * point2.y)
7
8
return [[x1, y1], [x2, y2]]
9
Advertisement
Answer
You first need to specify an origin point, the rotation will be created around that point. You can adapt your code and use something like this:
JavaScript
1
13
13
1
def rotate(origin, point, angle):
2
"""
3
Rotate a point counterclockwise by a given angle around a given origin.
4
5
The angle should be given in radians.
6
"""
7
ox, oy = origin.x, origin.y
8
px, py = point.x, point.y
9
10
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
11
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
12
return Point(qx, qy)
13
You can then plot some point and see the results with:
JavaScript
1
9
1
x1 = Point(0, 0)
2
x2 = Point(5, 5)
3
mid_point = Point((x1.x + x2.x) / 2, (x1.y + x2.y) / 2)
4
plt.plot([x1.x, x2.x], [x1.y, x2.y], c='red')
5
x1 = rotate(mid_point, x1, math.radians(30))
6
x2 = rotate(mid_point, x2, math.radians(30))
7
plt.plot([x1.x, x2.x], [x1.y, x2.y], c='blue')
8
plt.show()
9
Where you can clearly see the rotation around the middle point between the two lines.