Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate image using pygame [duplicate]

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?

like image 743
Pratik Singhal Avatar asked Oct 11 '13 11:10

Pratik Singhal


People also ask

How do I rotate an image in pygame?

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.

Can you flip an image in pygame?

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.

How do you rotate the surface in pygame?

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).


1 Answers

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))
        ...
like image 112
sloth Avatar answered Oct 11 '22 16:10

sloth