1

I am trying to make my polygon rotate able. But when I input new_point the report is new_point aren't define. This is giving me a headache

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 had try to used pygame.tranfrom.rotate() and replace "new_point" with different value but the program still refuse to run

Need_help
  • 31
  • 4

1 Answers1

3

There is no need to create a pygame.Surface and to use pygame.transform.rotate to rotate the points of a polygon. You can use pygame.math.Vectore2.rotate tor create a rotated list of points.

  • define the pivot point (e.g. center of the polygon)
  • calculate the vectors from the pivot point to the points of the polygon
  • use pygame.math.Vectore2.rotate to rotate the vectors
  • add the pivot point to the rotated vectors
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

Minimal example:

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174