首页 > 解决方案 > 我应该如何使用pygame连续旋转图像?

问题描述

我有一个想要连续旋转的图像。

我想在特定的时间间隔后将它旋转一定的角度。但是,我想实现一个功能,在我单击特定键的那一刻,向图像头部指向的方向射击子弹。

那么在那个时刻,我应该如何在旋转的图像中保持我的头部轨迹呢?

标签: pythonpygame

解决方案


创建旋转图像的计算成本很高。这是在你的程序进入主循环之前应该做的事情。

“连续旋转”的图像实际上是一组动画帧,每个帧都比前一个帧提前了一定程度。

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上面类中的当前旋转索引( the )。例如,想象一个只有 4 帧的“旋转”——上/右/下/左。


推荐阅读