在Pygame中旋转图像

时间:2014-06-28 00:51:42

标签: python python-2.7 pygame

我之前已经问过这个问题,主要是因为我已经阅读了几篇关于这个主题的帖子,但我无法达到我想要的效果。据我所知,我的数学和代码是正确的。基本上,我正在创造一个头顶90度射击游戏,我希望玩家的图像旋转以面向鼠标。就像现在一样,图像将左右轻微旋转,但不能完全旋转以面向鼠标。正如我所说,我已经查看过教程,但我无法弄清楚这一点。任何帮助或指示将不胜感激。我的代码如下。谢谢!

    #Import pygame
    import pygame, sys
    from pygame.locals import *
    import math

    #Initialize pygame
    pygame.init()


   #System variables
   running = True
   dispWidth = 800
   dispHeight = 600
   pygame.mouse.set_visible(False)
   pygame.key.set_repeat(1, 50)

   player = pygame.image.load('resources/player_handgun.png')
   playerX = 50
   playerY = 50

   background = pygame.image.load('resources/grass.png')

   crosshair = pygame.image.load('resources/crosshair.png')

   gameScreen = pygame.display.set_mode( ( dispWidth, dispHeight) )
   pygame.display.set_caption('Zombie Shooter')
   gameScreen.blit( player, ( playerX, playerY))
   gameScreen.blit( background, ( 0, 0))

   pygame.display.update()

   #def updateScreen():
   #    playerX = playerX + movement

   #Game Loop
   while running:
     blue = (0,0,255)


     velX = 0
     velY = 0

     for event in pygame.event.get():
         if event.type == QUIT:
             pygame.quit()
             sys.exit()
         elif event.type == pygame.KEYDOWN:
             if event.key == pygame.K_d:
                 velX = 10
             if event.key == pygame.K_a:
                 velX = (-10)
             if event.key == pygame.K_w:
                 velY = (-10)
             if event.key == pygame.K_s:
                 velY = 10

     playerX = playerX + velX
     playerY = playerY + velY
     pos = (pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])
     playerDirection = math.atan2(playerY-pos[1], playerX-pos[0])

     char = pygame.transform.rotate(player, playerDirection)
     gameScreen.blit( background, (0, 0))
     gameScreen.blit( char,(playerX,playerY))


     gameScreen.blit( crosshair, (pos[0]-16,pos[1]-16))


     print playerDirection
     pygame.display.update()

1 个答案:

答案 0 :(得分:1)

pygame.transform.rotate以度为单位取角度,而math.atan2以弧度为单位返回角度,因此您需要在两者之间进行转换。

playerDirection = math.degrees(math.atan2(playerY-pos[1], playerX-pos[0]))

链接: