如何在pygame中的按键上旋转多边形?

问题描述 投票:0回答:1

我正在尝试使我的多边形能够旋转。但是当我输入 new_point 时,报告是 new_point 未定义。这让我头疼

def xoay_hinh(key):
    lx, ly = zip(*hinh)
    min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly)
    new_hinh = hinh
    if key[pygame.K_r]:
        cx = ((max_x - min_x)/2) + min_x
        cy = ((max_y - min_y)/2) + min_y
        for point in hinh and for new_point in new_hinh :
            new_point[0] = cy - point[1]
            new_point[1] = cy + point[0] - cx
            point[0] = new_point[0]
            point[1] = new_point[1]

T 曾尝试使用

pygame.tranfrom.rotate()
并用不同的值替换“new_point”,但程序仍然拒绝运行

pygame rotation polygon
1个回答
4
投票

无需创建

pygame.Surface
并使用
pygame.transform.rotate
来旋转多边形的点。您可以使用
pygame.math.Vector2.rotate
创建点的旋转列表。

  • 定义枢轴点(例如多边形的中心)
  • 计算从枢轴点到多边形各点的向量
  • 使用
    pygame.math.Vector2.rotate
    旋转向量
  • 将枢轴点添加到旋转向量
def rotate_points_around_pivot(points, pivot, angle):
    pp = pygame.math.Vector2(pivot)
    rotated_points = [
        (pygame.math.Vector2(x, y) - pp).rotate(angle) + pp for x, y in points]
    return rotated_points

最小示例:

import pygame

def rotate_points_around_pivot(points, pivot, angle):
    pp = pygame.math.Vector2(pivot)
    rotated_points = [
        (pygame.math.Vector2(x, y) - pp).rotate(angle) + pp for x, y in points]
    return rotated_points

def draw_rotated_polygon(surface, color, points, angle, pivot=None):
    if pivot == None:
        lx, ly = zip(*points)
        min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly)
        bounding_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
        pivot = bounding_rect.center
    rotated_points = rotate_points_around_pivot(points, pivot, angle)
    pygame.draw.polygon(surface, color, rotated_points)

pygame.init()
window = pygame.display.set_mode((250, 250))
clock = pygame.time.Clock()
pivot = (125, 125)
size = 90
points = [(0, -1), (-0.8660, 0.5), (0.8660, 0.5)]
points = [(pivot[0] + x * size, pivot[1] + y * size) for x, y in points]
angle = 0
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    key = pygame.key.get_pressed()
    if key[pygame.K_r]:
        angle += 1

    window.fill("black")
    draw_rotated_polygon(window, "white", points, angle, pivot)
    pygame.display.flip()

pygame.quit()
© www.soinside.com 2019 - 2024. All rights reserved.