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

如何在Pygame中按键旋转多边形?报错new_point未定义

多边形旋转问题的修复方案

先解决「new_point未定义」的直接错误

你的循环写法完全不符合Python语法,for point in hinh and for new_point in new_hinh 这种写法根本跑不起来,直接导致new_point没被正确声明,这就是报错的根源。另外new_hinh = hinh只是把两个变量指向同一个列表,不是复制出新列表,修改的时候会直接改动原数据,这也会出问题。

修正后的旋转实现代码

先把旋转逻辑用正确的语法和数学公式写好:

def xoay_hinh(key):
    global hinh  # 确保能修改全局的hinh变量
    if key[pygame.K_r]:
        # 计算多边形的中心坐标
        lx, ly = zip(*hinh)
        cx = (min(lx) + max(lx)) / 2
        cy = (min(ly) + max(ly)) / 2
        
        # 创建新的点列表,避免直接修改原列表
        new_hinh = []
        # 用标准旋转矩阵(这里是逆时针旋转90度,可替换为任意角度计算)
        for (x, y) in hinh:
            # 先把点平移到原点,旋转后再平移回中心
            dx = x - cx
            dy = y - cy
            # 逆时针旋转90度的计算:x' = -dy, y' = dx
            new_x = -dy + cx
            new_y = dx + cy
            new_hinh.append([new_x, new_y])
        
        # 替换原多边形数据
        hinh = new_hinh

关于pygame.transform.rotate的正确用法

你之前用这个函数没成功,大概率是因为这个函数是用来旋转Surface对象的,不是直接旋转坐标点。如果你的多边形是画在Surface上的,可以这么用:

# 假设你有一个绘制好多边形的surface
rotated_surface = pygame.transform.rotate(your_surface, angle)
# 获取旋转后的矩形位置,避免偏移
rotated_rect = rotated_surface.get_rect(center=your_surface.get_rect().center)
# 把旋转后的surface画到屏幕上
screen.blit(rotated_surface, rotated_rect)

注意:每次旋转都会让图像轻微模糊,建议保留原始Surface,每次都从原始图旋转,不要重复旋转已经旋转过的图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:40:27