如何在Pygame中围绕指定点旋转坐标轴,基于DDA算法绘制正多边形
解决方法
你不需要直接旋转全局坐标系,只需要对当前的两个边端点应用绕中心点的二维旋转变换即可,具体操作如下:
实现原理
任意点(x, y)绕中心点(cx, cy)旋转θ角度的计算逻辑:
- 先将坐标系平移到以
(cx, cy)为原点:tx = x - cx,ty = y - cy - 应用旋转公式:
rx = tx * cosθ - ty * sinθ ry = tx * sinθ + ty * cosθ - 再平移回原坐标系得到旋转后的坐标:
new_x = rx + cx,new_y = ry + cy
补充代码修改
你只需要在DrawPoly函数的循环中加入以下旋转逻辑即可:
# 先把角度转成弧度,math库三角函数使用弧度计算 rotate_rad = math.radians(sideAngle) cos_val = math.cos(rotate_rad) sin_val = math.sin(rotate_rad) for i in range(n-1): # 旋转第一个端点 tx1 = bv1x - cx ty1 = bv1y - cy rx1 = tx1 * cos_val - ty1 * sin_val ry1 = tx1 * sin_val + ty1 * cos_val bv1x, bv1y = rx1 + cx, ry1 + cy # 旋转第二个端点 tx2 = bv2x - cx ty2 = bv2y - cy rx2 = tx2 * cos_val - ty2 * sin_val ry2 = tx2 * sin_val + ty2 * cos_val bv2x, bv2y = rx2 + cx, ry2 + cy drawDDA((bv1x, bv1y), (bv2x, bv2y), color)
额外注意事项
- 你的代码开头需要补全依赖导入:
import pygame from pygame import gfxdraw import sys import os import math mainloop函数中if event.type == pygame.QUIT:的缩进错误,需要缩进一层到for event的循环内部:def mainloop(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
修改完成后运行即可生成指定边数的正多边形。
内容的提问来源于stack exchange,提问作者newbie
相关产品推荐
相关产品推荐

