How can I rotate a group of pygame objects (either rectangles or images)

An image is worth a thousand words, so ultimately my question is: β€œHow can I achieve this?”:

enter image description here

Intuitively, I thought that this could be achieved by defining a surface in the main pygame.display.set_mode object defined by pygame.display.set_mode , drawing (or blitting) what is needed on that surface, and then rotating it using pygame.transform.rotate . I suggested that static points can be directly attached to the screen object in the code below, which is the object returned by the pygame.display.set_mode function.

So I prepared the following test code, but I do not see the rotation. What am I doing wrong?

 #!/usr/bin/env python import pygame as pg from pygame.locals import * SIZE = (800, 600) BGCOL = (128, 128, 128) STIMCOL = (80, 255, 80) screen = pg.display.set_mode((SIZE), HWSURFACE | DOUBLEBUF) screen.fill(BGCOL) surf = pg.Surface((200, 200), flags=HWSURFACE) surf.fill(BGCOL) pg.draw.rect(surf, STIMCOL, (10, 20, 40, 50)) pg.draw.rect(surf, STIMCOL, (60, 70, 80, 90)) screen.blit(surf, (100, 100)) pg.display.flip() running = True while running: pg.transform.rotate(surf, -1) pg.display.flip() 

Of course, if there is a better way to do this, I am all ears. Perhaps sprite groups are a good way to go? (Although I have never used them before ... = /)

Thanks!

+4
source share
1 answer

You have some errors in the code:

pygame.transform.rotate (surface, angle) returns a rotating surface

and you don’t hit the surface during the cycle. Therefore, your code should look like this:

 import pygame as pg from pygame.locals import * SIZE = (800, 600) BGCOL = (128, 128, 128) STIMCOL = (80, 255, 80) screen = pg.display.set_mode((SIZE), HWSURFACE | DOUBLEBUF) screen.fill(BGCOL) surf = pg.Surface((200, 200), flags=HWSURFACE) surf.fill(BGCOL) pg.draw.rect(surf, STIMCOL, (10, 20, 40, 50)) pg.draw.rect(surf, STIMCOL, (60, 70, 80, 90)) screen.blit(surf, (100, 100)) pg.display.flip() running = True while running: surf = pg.transform.rotate(surf, -1) # updating rotation on the surface screen.blit(surf, (100, 100)) #bliting the resulting image every frame pg.display.flip() 

EDIT: after looking at comments in pygame docs, there are many problems with resizing an image when rotated by only 90 degrees. You must follow the rotation and rotate the image from scratch at an angle.

+2
source

All Articles