如何使用pygame中的键旋转我的图像?

时间:2017-12-05 20:14:57

标签: python image rotation pygame key

我试图让图像(透明图像)旋转我按下的按键。 I.E.我想让我的球员上下旋转(他从头上射击),但我并没有真正有一个关于如何编码的准确指南。如果有人能帮助我,我将不胜感激。此外,当我按住键时,我希望头部能够平稳地上下旋转(瞄准)。代码如下:

import pygame

pygame.init()

white = (255,255,255)
BLACK = (0,0,0)
red = (255,0,0)


gameDisplay = pygame.display.set_mode((640,360))

background = pygame.image.load('background.jpg').convert()

player = pygame.image.load('BigShagHoofdz.png') #this must be rotateable

pygame.display.set_caption('Leslie is Lauw')
clock = pygame.time.Clock()


gameDisplay.blit(background, [0,0])
gameDisplay.blit(player, [-1,223])
pygame.display.update()

FPS = 60

direction = "Down"

def head():
    if direction == "Down":
        playerhead = player
    if direction == "Up":
        playerhead = pygame.transform.rotate(player, 60)



def gameLoop():
    global direction
    gameExit = False


    while gameExit==False: 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            gameExit = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            gameExit = True

            if event.key == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                direction = "Up"
                elif event.key == pygame.K_DOWN:
                direction = "Down"

clock.tick(60)
pygame.quit()
quit()

当我按下向上或向下键时,它应该只向上或向下旋转,当它按下或向上时可以让它平滑。

1 个答案:

答案 0 :(得分:2)

如果您只想在普通图像和旋转图像之间切换,可以在while循环之前创建旋转版本,然后只需按下按键即可切换图像。

import pygame

pygame.init()

gameDisplay = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
# The normal image/pygame.Surface.
player_image = pygame.Surface((30, 50), pygame.SRCALPHA)
player_image.fill((0, 100, 200))
pygame.draw.circle(player_image, (0, 50, 100), (15, 20), 12)
# The rotated image.
player_rotated = pygame.transform.rotate(player_image, 60)

FPS = 60

def gameLoop():
    player = player_image
    player_pos = [100, 223]
    gameExit = False

    while gameExit == False: 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            elif event.type == pygame.KEYDOWN:
                # Assign the current image to the `player` variable.
                if event.key == pygame.K_UP:
                    player = player_image
                elif event.key == pygame.K_DOWN:
                    player = player_rotated

        gameDisplay.fill((30, 30, 30))
        gameDisplay.blit(player, player_pos)

        pygame.display.flip()
        clock.tick(60)

gameLoop()
pygame.quit()