I am new to pygame and want to write some code that simply rotates an image by 90 degrees every 10 seconds. My code looks like this:
import pygame
import time
from pygame.locals import *
pygame.init()
display_surf = pygame.display.set_mode((1200, 1200))
image_surf = pygame.image.load("/home/tempuser/Pictures/desktop.png").convert()
imagerect = image_surf.get_rect()
display_surf.blit(image_surf,(640, 480))
pygame.display.flip()
start = time.time()
new = time.time()
while True:
end = time.time()
if end - start > 30:
break
elif end - new > 10:
print "rotating"
new = time.time()
pygame.transform.rotate(image_surf,90)
pygame.display.flip()
This code is not working ie the image is not rotating, although "rotating" is being printed in the terminal every 10 seconds. Can somebody tell me what I am doing wrong?
To rotate the image we use the pygame. transform. rotate(image, degree) method where we pass the image that we are going to rotate and the degree by which rotation is to be done.
To flip the image we need to use pygame. transform. flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs.
Surface ) can be rotated by pygame. transform. rotate . This is cause, because the bounding rectangle of a rotated image is always greater than the bounding rectangle of the original image (except some rotations by multiples of 90 degrees).
pygame.transform.rotate
will not rotate the Surface
in place, but rather return a new, rotated Surface
. Even if it would alter the existing Surface
, you would have to blit it on the display surface again.
What you should do is to keep track of the angle in a variable, increase it by 90
every 10 seconds, and blit the new Surface
to the screen, e.g.
angle = 0
...
while True:
...
elif end - new > 10:
...
# increase angle
angle += 90
# ensure angle does not increase indefinitely
angle %= 360
# create a new, rotated Surface
surf = pygame.transform.rotate(image_surf, angle)
# and blit it to the screen
display_surf.blit(surf, (640, 480))
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With