以角度旋转正方形

时间:2014-05-05 00:12:36

标签: python rotation computational-geometry angle

我有一个中心为x0,y0的正方形。我希望将该正方形的顶点旋转一个以度数表​​示的给定角度(θ),并以顺时针方向返回新旋转的顶点。我正在使用此approach来旋转应用于每个顶点的单个点

围绕点(x0,y0)旋转点(px,py),你得到角度θ:

p'x = cos(theta) * (px-x0) - sin(theta) * (py-y0) + x0
p'y = sin(theta) * (px-x0) + cos(theta) * (py-y0) + y0

where: 
px, py = coordinate of the point
y0, x0, = centre of rotation
theta = angle of rotation

我在Python中编写了一个函数,其中的参数是:x,y(=方形的中心),方形的边和theta_degree(以度为单位的旋转角度)但是返回是逆时针方向

from math import cos, sin

def get_square_plot(x, y, side, theta_degree=0):
    theta = theta_degree * pi/180
    xa = x-side/2
    ya = y+side/2
    xb = x+side/2
    yb = y+side/2
    xc = x+side/2
    yc = y-side/2
    xd = x-side/2
    yd = y-side/2
    xa_new = cos(theta) * (xa - x) - sin(theta) * (ya - y) + x
    ya_new = sin(theta) * (xa - x) - cos(theta) * (ya - y) + y
    xb_new = cos(theta) * (xb - x) - sin(theta) * (yb - y) + x
    yb_new = sin(theta) * (xb - x) - cos(theta) * (yb - y) + y
    xc_new = cos(theta) * (xc - x) - sin(theta) * (yc - y) + x
    yc_new = sin(theta) * (xc - x) - cos(theta) * (yc - y) + y
    xd_new = cos(theta) * (xd - x) - sin(theta) * (yd - y) + x
    yd_new = sin(theta) * (xd - x) - cos(theta) * (yd - y) + y
    return [(xa_new, ya_new),(xb_new, yb_new),(xc_new, yc_new),(xd_new, yd_new)]

get_square_plot(0, 0, 10, 0)
[(-5.0, -5.0), (5.0, -5.0), (5.0, 5.0), (-5.0, 5.0)]

而不是

[(-5.0, 5.0), (5.0, 5.0), (5.0, -5.0), (-5.0, -5.0)]

2 个答案:

答案 0 :(得分:2)

这是一件很简单的事情 - 你的所有y值的公式都是错误的。

应该是:

ya_new = sin(theta) * (xa - x) + cos(theta) * (ya - y) + y

添加而不是减法。

答案 1 :(得分:1)

也不要忘记几何模块。它可以处理各种基本形状并处理平移,旋转等...

可以使用RegularPolygon构造一个正方形。它是通过从中心定位给定半径的顶点来实现的;得到一个给定边长的正方形除以sqrt(2)。这是一个旋转菱形方向的功能,使侧面平行于轴,然后旋转所需的角度,a

>>> Square = lambda c, r, a: RegularPolygon(c, r/sqrt(2), 4, -rad(a) - pi/4)
>>> Square((0,0),10,0).vertices
[Point(5, -5), Point(5, 5), Point(-5, 5), Point(-5, -5)]
>>> [w.n(2) for w in Square((0,0),10,1).vertices]
[Point(4.9, -5.1), Point(5.1, 4.9), Point(-4.9, 5.1), Point(-5.1, -4.9)]

请注意,轻微的CW旋转1度(-rad(1))会使第一个顶点更接近y轴,并且会像我们预期的那样略低一些。您还可以输入角度的符号:

>>> from sympy.utilities.misc import filldedent
>>> print filldedent(Square((0,0),10,a).vertices)

[Point(5*sqrt(2)*cos(pi*a/180 + pi/4), -5*sqrt(2)*sin(pi*a/180 +
pi/4)), Point(5*sqrt(2)*sin(pi*a/180 + pi/4), 5*sqrt(2)*cos(pi*a/180 +
pi/4)), Point(-5*sqrt(2)*cos(pi*a/180 + pi/4), 5*sqrt(2)*sin(pi*a/180
+ pi/4)), Point(-5*sqrt(2)*sin(pi*a/180 + pi/4),
-5*sqrt(2)*cos(pi*a/180 + pi/4))]

您还可以通过旋转点-theta(CW)检查点旋转公式:

>>> var('px py theta x0 y0')
(px, py, theta, x0, y0)
>>> R = Point(px,py).rotate(-theta, Point(x0,y0))
>>> R.x
x0 + (px - x0)*cos(theta) + (py - y0)*sin(theta)
>>> R.y
y0 + (-px + x0)*sin(theta) + (py - y0)*cos(theta)