在Python中从中点创建方形多边形(随机定向)
我有一个中点(x,y),我需要使用二维(随机)平面旋转创建一个具有随机方向的方形多边形在Python中从中点创建方形多边形(随机定向),python,function,computational-geometry,Python,Function,Computational Geometry,我有一个中点(x,y),我需要使用二维(随机)平面旋转创建一个具有随机方向的方形多边形 def get_square_plot(x, y, side): return [(x-(side/2), y+(side/2)), (x+(side/2), y+(side/2)), (x+(side/2), y-(side/2)), (x-(side/2), y-(side/2))] 此函数用于创建没有特定方向的方形多边形的顶点。我希望改进此函数,增加随机旋转这些顶点的可能性(如果可能,以特定角
def get_square_plot(x, y, side):
return [(x-(side/2), y+(side/2)), (x+(side/2), y+(side/2)), (x+(side/2), y-(side/2)), (x-(side/2), y-(side/2))]
此函数用于创建没有特定方向的方形多边形的顶点。我希望改进此函数,增加随机旋转这些顶点的可能性(如果可能,以特定角度旋转)如果我正确理解了您的意思,应该可以执行您想要的操作:
from math import sin, cos, radians
def rotated_square(cx, cy, size, degrees=0):
""" Calculate coordinates of a rotated square centered at 'cx, cy'
given its 'size' and rotation by 'degrees' about its center.
"""
h = size/2
l, r, b, t = cx-h, cx+h, cy-h, cy+h
a = radians(degrees)
cosa, sina = cos(a), sin(a)
pts = [(l, b), (l, t), (r, t), (r, b)]
return [(( (x-cx)*cosa + (y-cy)*sina) + cx,
(-(x-cx)*sina + (y-cy)*cosa) + cy) for x, y in pts]
print rotated_square(50, 50, 100)
输出:
[(0.0,0.0),(0.0,100.0),(100.0,100.0),(100.0,0.0)]
请注意,在一般情况下,生成的坐标不会是整数
有效的方法是首先将每个坐标平移到原点,减去cx,cy,将其旋转角度,然后将其反平移回相同的量。这对于补偿旋转公式通常相对于坐标系原点的事实是必要的。确定四个角坐标后,可以使用简单的二维矩阵旋转相对于原点(或中点)旋转它们: (搜索二维旋转方程) 您可以为cos/sin函数使用内置的Python数学库:第9.2.3节
Math.cos(theta)
Math.sin(theta)
我希望这是有用的吉安尼:如果这是你想要的,请考虑接受它。如果没有,请说明原因。
Math.cos(theta)
Math.sin(theta)