0

I'm trying to build a simple game and so far I'm just learning the basics.
I'm trying to draw a rectangle tilted 45°, but I couldn't figure how to keep it centered even after reading some previous question here on SO.
So I tried making a rectangle that keeps rotating; this is the corresponding code.

alpha=0
while True:
    w, h=screen.get_size()
    s=pygame.Surface((w/2, h))
    pygame.draw.rect(s, col, (300,150,50,10))
    s=pygame.transform.rotozoom(s, alpha, 1)
    alpha+=2
    s.set_colorkey((0,0,0))
    background.blit(s, (0, 0))
    # flip screen, etc 

The surface should keep rotating forever around some center (I wanted to use this to understand clearly which it was), but it moves in an irregular way.
This is the video of what happens [...].

EDIT:marked as duplicate, I'm removing the video link

dbac
  • 328
  • 1
  • 10

1 Answers1

0

Rotating a rectangle (not image) in pygame provides you an answer:

Example code:

import pygame as py  

# define constants  
WIDTH = 500  
HEIGHT = 500  
FPS = 30  

# define colors  
BLACK = (0 , 0 , 0)  
GREEN = (0 , 255 , 0)  

# initialize pygame and create screen  
py.init()  
screen = py.display.set_mode((WIDTH , HEIGHT))  
# for setting FPS  
clock = py.time.Clock()  

rot = 0
rot_speed = 3

# define a surface (RECTANGLE)  
image_orig = py.Surface((100 , 100))  
# for making transparent background while rotating an image  
image_orig.set_colorkey(BLACK)  
# fill the rectangle / surface with green color  
image_orig.fill(GREEN)  
# creating a copy of orignal image for smooth rotation  
image = image_orig.copy()  
image.set_colorkey(BLACK)  
# define rect for placing the rectangle at the desired position  
rect = image.get_rect()  
rect.center = (WIDTH // 2 , HEIGHT // 2)  
# keep rotating the rectangle until running is set to False  
running = True  
while running:  
    # set FPS  
    clock.tick(FPS)  
    # clear the screen every time before drawing new objects  
    screen.fill(BLACK)  
    # check for the exit  
    for event in py.event.get():  
        if event.type == py.QUIT:  
            running = False  

    # making a copy of the old center of the rectangle  
    old_center = rect.center  
    # defining angle of the rotation  
    rot = (rot + rot_speed) % 360  
    # rotating the orignal image  
    new_image = py.transform.rotate(image_orig , rot)  
    rect = new_image.get_rect()  
    # set the rotated rectangle to the old center  
    rect.center = old_center  
    # drawing the rotated rectangle to the screen  
    screen.blit(new_image , rect)  
    # flipping the display after drawing everything  
    py.display.flip()  

py.quit()  
Noah
  • 445
  • 4
  • 19