[英]Function for rotating 2d objects?
是否有可能在python中編寫一個函數,可以旋轉任何2d結構,參數只是結構中點的坐標(x,y)? 軸,速度和方向將包括其他參數。
根據我的理解,只有通過計算對稱點和軸的點距離才有可能,因此它總是會變化,因此除了由標准形狀(三角形,矩形,正方形等)組成的2d結構外,它是不可能的。
很好的例子將不勝感激。
首先,我們需要一個函數來旋轉原點周圍的點。
當我們將原點周圍的點(x,y)旋轉θ度時,我們得到坐標:
(x * cos(theta)-y * sin(theta),x * sin(theta)+ y * cos(theta))
如果我們想圍繞原點以外的點旋轉它,我們只需要移動它,使中心點成為原點。 現在,我們可以編寫以下函數:
from math import sin, cos, radians
def rotate_point(point, angle, center_point=(0, 0)):
"""Rotates a point around center_point(origin by default)
Angle is in degrees.
Rotation is counter-clockwise
"""
angle_rad = radians(angle % 360)
# Shift the point so that center_point becomes the origin
new_point = (point[0] - center_point[0], point[1] - center_point[1])
new_point = (new_point[0] * cos(angle_rad) - new_point[1] * sin(angle_rad),
new_point[0] * sin(angle_rad) + new_point[1] * cos(angle_rad))
# Reverse the shifting we have done
new_point = (new_point[0] + center_point[0], new_point[1] + center_point[1])
return new_point
一些產出:
print(rotate_point((1, 1), 90, (2, 1)))
# This prints (2.0, 0.0)
print(rotate_point((1, 1), -90, (2, 1)))
# This prints (2.0, 2.0)
print(rotate_point((2, 2), 45, (1, 1)))
# This prints (1.0, 2.4142) which is equal to (1,1+sqrt(2))
現在,我們只需要使用前面的函數旋轉多邊形的每個角落:
def rotate_polygon(polygon, angle, center_point=(0, 0)):
"""Rotates the given polygon which consists of corners represented as (x,y)
around center_point (origin by default)
Rotation is counter-clockwise
Angle is in degrees
"""
rotated_polygon = []
for corner in polygon:
rotated_corner = rotate_point(corner, angle, center_point)
rotated_polygon.append(rotated_corner)
return rotated_polygon
示例輸出:
my_polygon = [(0, 0), (1, 0), (0, 1)]
print(rotate_polygon(my_polygon, 90))
# This gives [(0.0, 0.0), (0.0, 1.0), (-1.0, 0.0)]
您可以通過首先平移(移動)所有點來旋轉平面上任意點的二維點陣列,使旋轉點成為原點(0, 0)
,將標准旋轉公式應用於每個點x和y坐標,然后通過與最初完成的完全相反的量來“翻譯”它們。
在計算機圖形學中,這通常通過使用稱為變換矩陣的東西來完成。
同樣的概念也可以很容易地擴展到使用三維點。
編輯:
請參閱我對問題的答案旋轉中心點周圍的線,給出兩個頂點,以獲得使用此技術的完全解決的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.