Rotate image using pygame

2020-02-28 06:50发布

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?

1条回答
冷血范
2楼-- · 2020-02-28 07:37

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))
        ...
查看更多
登录 后发表回答