繁体   English   中英

以角度旋转正方形

[英]Rotate a square by an angle in degree

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

将角度(x0,y0)绕点(px,py)旋转角度theta您将获得:

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)]

这很简单-您对所有y值的公式都有误。

它应该是:

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

加法而不是减法。

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

可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM