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

Pygame三角形跟随鼠标旋转时出现无输入自动移动问题求助

问题根本原因
  • 旋转用的基准三角形重心不在坐标原点:你定义的三个基准顶点[(-0.5, -0.866), (-0.5, 0.866), (1.1, 0.0)]的重心计算下来为(0.1/3, 0),并非(0,0)。每次调用_rotate方法时,基于当前三角形重心做旋转变换后,得到的新三角形重心会相比原重心产生固定偏移,每帧执行一次update就累积一次偏移,最终表现为无操作时三角形自动移动。
  • 次要笔误:update方法中调用getCenter时传入了mouseP参数,但getCenter的定义没有接收参数,部分Python版本中会直接抛出参数不匹配异常。
修复方案
  1. 修正基准三角形的顶点坐标,保证其重心在原点:把第三个顶点的x值从1.1改为1.0,修改后的基准顶点重心刚好在原点,旋转变换后新三角形的重心和变换前的中心完全重合,不会产生偏移。
  2. 删除update方法中调用getCenter时多余的mouseP参数。
  3. 可选优化:如果担心长期运行的浮点数精度累积问题,可以单独存储三角形的重心坐标作为属性,不要每次都通过三个顶点计算,避免精度误差累积。

修正后核心代码示例

def _rotate(self, center, scale, mouse_pos):
    dx = mouse_pos[0] - center[0]
    dy = mouse_pos[1] - center[1]
    len = math.sqrt(dx * dx + dy * dy)
    dx, dy = (dx * scale / len, dy * scale / len) if len > 0 else (1, 0)
    # 修正基准三角形重心为原点,将第三个点x从1.1改为1.0
    pts = [(-0.5, -0.866), (-0.5, 0.866), (1.0, 0.0)]
    pts = [(center[0] + p[0] * dx + p[1] * dy, center[1] + p[0] * dy - p[1] * dx) for p in pts]
    return pts

def update(self):
    # point to mouse
    mouseP = pygame.mouse.get_pos()
    # 删除多余的mouseP传参
    center = self.getCenter()
    points = self._rotate(center, 12, mouseP)
    self.x1 = points[0][0]
    self.x2 = points[1][0]
    self.x3 = points[2][0]
    self.y1 = points[0][1]
    self.y2 = points[1][1]
    self.y3 = points[2][1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:27:03