栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

旋转2D对象的功能?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

旋转2D对象的功能?

首先,我们需要一个绕原点旋转点的函数。

当我们绕原点旋转一个点(x,y)theta度时,我们得到的坐标为:

(x cosθ-y sinθ,x sinθ+ y cosθ)

如果要围绕原点以外的其他点旋转它,只需移动它,使中心点成为原点。现在,我们可以编写以下函数:

from math import sin, cos, radiansdef 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)]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652951.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号