我有一张想要不断旋转的图片。
我考虑在特定时间间隔后通过某个角度来旋转它。然而,当我点击特定按键时,我希望实现一个功能,即可以朝着我的头部所指方向发射一颗子弹。
那么在那个时刻,我应该如何跟踪旋转图像中的头部?
创建旋转图像的计算开销很大。 这应该在程序进入其主循环之前完成一次。
"持续旋转"图像实际上是一组动画帧,每个帧都比之前向前推进一些度数。
Pygame函数pygame.transform.rotate()
将旋转图像。 在您的情况下,确定某个步进角度,然后创建N个图像可能会很有用。
例如,如果您想要12帧旋转动画,则需要创建11帧更多的动画,每个动画都旋转360 / 12度(是否存在差错?)。
这为我们提供了一个简单的精灵类,在实例化时预先创建框架。 显然,如果您有很多精灵,重新计算每个精灵的相同帧是没有意义的,但它作为示例。
class RotatingSprite( pygame.sprite.Sprite ):
def __init__( self, bitmap, rot_count=12 ):
pygame.sprite.Sprite.__init__( self )
self.rect = bitmap.get_rect()
self.rect.center = ( random.randrange( 0, WINDOW_WIDTH ), random.randrange( 0, WINDOW_HEIGHT ) )
# start with zero rotation
self.rotation = 0
self.rotations = [ bitmap ]
self.angle_step = rot_count
self.angle_slots = 360 // self.angle_step
# pre-compute all the rotated images, and bitmap collision masks
for i in range( 1, self.angle_slots ):
rotated_image = pygame.transform.rotate( bitmap, self.ANGLE_STEP * i )
self.rotations.append( rotated_image )
self._setRotationImage( 0 ) # sets initial image & rect
def rotateRight( self ):
if ( self.rotation == 0 ):
self._setRotationImage( self.angle_slots - 1 )
else:
self._setRotationImage( self.rotation - 1 )
def rotateLeft( self ):
if ( self.rotation == self.angle_slots - 1 ):
self._setRotationImage( 0 )
else:
self._setRotationImage( self.rotation + 1 )
def _setRotationImage( self, rot_index ):
""" Set the sprite image to the correct rotation """
rot_index %= self.angle_slots
self.rotation = rot_index
# Select the pre-rotated image
self.image = self.rotations[ rot_index ]
# We need to preserve the centre-position of the bitmap,
# as rotated bitmaps will (probably) not be the same size as the original
centerx = self.rect.centerx
centery = self.rect.centery
self.rect = self.image.get_rect()
self.rect.center = ( centerx, centery )
def update( self ):
self.rotateRight() # do something
你当然可以在图形软件中预先制作旋转位图的12个帧,然后在运行时只需加载它们。我喜欢上述方法,因为如果你决定转移到24帧,只需更改一个参数即可。
图像“面向”的方向就是上述类中的当前旋转索引(self.rotation
)。例如,想象一下只有4个帧 - 上/右/下/左的“旋转”。