You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定角度旋转线段?旋转矩阵及Python代码失效问题

线段旋转问题的修正方案

你的代码存在几个关键问题,导致旋转功能无法正常工作,以下是问题分析和修正方案:

问题点

  • 参数名不匹配:函数定义参数为point和point2,但代码中使用point1,会触发变量未定义错误。
  • 旋转基准错误:当前代码直接绕坐标原点旋转,而实际需求通常是绕线段的端点或中点旋转,直接旋转会导致线段位置偏离预期。
  • 角度参数拼写失误:angel应为angle(虽不影响运行,但属于不良编码习惯)。

正确旋转逻辑

旋转线段的标准步骤:

  1. 确定旋转中心(比如线段端点p1或中点)
  2. 将所有点平移,使旋转中心与原点重合(点坐标减去旋转中心坐标)
  3. 对平移后的点应用旋转矩阵
  4. 将旋转后的点平移回原位置(加上旋转中心坐标)

修正后的代码(以p1为旋转中心)

from math import cos, sin, radians

def rotate(point1, point2, angle):
    # 设定旋转中心为point1
    cx, cy = point1.x, point1.y
    
    # 平移点到原点坐标系
    x1_trans = point1.x - cx
    y1_trans = point1.y - cy
    x2_trans = point2.x - cx
    y2_trans = point2.y - cy
    
    theta = radians(angle)
    cos_theta = cos(theta)
    sin_theta = sin(theta)
    
    # 应用旋转矩阵
    x1_rot = cos_theta * x1_trans - sin_theta * y1_trans
    y1_rot = sin_theta * x1_trans + cos_theta * y1_trans
    x2_rot = cos_theta * x2_trans - sin_theta * y2_trans
    y2_rot = sin_theta * x2_trans + cos_theta * y2_trans
    
    # 平移回原坐标系
    x1_final = x1_rot + cx
    y1_final = y1_rot + cy
    x2_final = x2_rot + cx
    y2_final = y2_rot + cy
    
    return [[x1_final, y1_final], [x2_final, y2_final]]

绕中点旋转的调整

如果需要绕线段中点旋转,只需修改旋转中心的计算:

cx = (point1.x + point2.x) / 2
cy = (point1.y + point2.y) / 2

补充说明

你使用的旋转矩阵是正确的,该矩阵默认表示逆时针旋转;若需要顺时针旋转,传入负角度即可。

内容的提问来源于stack exchange,提问作者Miumen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:05:47