python - 为什么我的程序在我添加旋转后变得非常迟钝,我该如何解决这个问题?

标签 python python-2.7 pygame pygame-surface pygame-clock

我正在使用 pygame 制作游戏,并且我有一个小行星类。当我将旋转添加到更新方法并运行程序时,小行星移动得非常缓慢和滞后,甚至它们的图像看起来也比以前更糟。

我不确定如何解决这个问题以及为什么会发生这种情况。这是类(class):

class enemy(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
    pygame.sprite.Sprite.__init__(self)
    self.width = width
    self.height = height
    self.speedx = random.randrange(-3,3)
    self.speedy = random.randrange(5,15)
    self.image = random.choice(meteor_image)
    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y
    self.rotation = 0
    self.rotation_speed = random.randrange(-8,8)
    self.last_update = pygame.time.get_ticks()

def draw(self,win):
    win.blit(self.image,(self.rect.x,self.rect.y))

def rotate(self):
    time_now = pygame.time.get_ticks()
    if time_now - self.last_update > 50:
        self.last_update = time_now
        self.rotation = (self.rotation + self.rotation_speed) % 360
        new_meteor_image = pygame.transform.rotate(self.image, self.rotation)
        old_center = self.rect.center
        self.image = new_meteor_image
        self.rect = self.image.get_rect()
        self.rect.center = old_center

def update(self):
    self.rotate()
    self.rect.y += self.speedy
    self.rect.x += self.speedx

在我添加旋转功能并在更新功能中添加“self.roatate()”之前,它很好,之后,它真的很卡。如何解决?

最佳答案

您正在拍摄原图,旋转它,然后旋转旋转后的图像。不要那样做。旋转过程会丢失信息,因此您每次都希望从原始的、未修改的版本开始旋转。

旋转也是一个繁重的操作。我建议创建一个缓存来存储旋转的图像,在开始时构建它,然后在需要显示时从该缓存中提取。

关于python - 为什么我的程序在我添加旋转后变得非常迟钝,我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55715025/

相关文章:

python - 如何根据另外两个给定图像对图像进行分类

python - 遍历Python列表并将数字输出到列表

python - 保存裁剪图像时出现奇怪的枕头异常

python - 为什么 __getitem__ 在 Python 3.5 中被调用而在 Python 2.7 中不被调用?

python - 如何使用 pygame 让 Sprite 跟随鼠标光标?

python - pygame 在失去生命时摇动窗口

python - 带条件保存文件名

Python 相当于 Perl 的 'w' 打包格式

python - Pandas 中的 sort_values() 方法

python - Pygame 多颗子弹不产生