我有一个用Pygame制作的游戏,并且我添加了一个“小”更新,当按下空格时,一个精灵会更改为另一个精灵,持续80ms,这会使整个游戏滞后(不仅是按下空格时,而且一直都是) 。有人可以帮忙吗? :)
以下是“更新”之前的一些代码:
man.py
class Man(Sprite):
def __init__(self, ai_settings, screen):
super().__init__()
self.screen = screen
# Load the image of the man and get its rect.
self.image = pygame.image.load('images/man_gun_large.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# Man firing gun sprite
self.fire = pygame.image.load('images/man_gun_large_fire.bmp')
self.fire_rect = self.fire.get_rect()
self.screen_fire_rect = self.screen.get_rect()
self.ai_settings = ai_settings
# Start each new man at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
self.fire_rect.centerx = self.screen_rect.centerx
self.fire_rect.top = self.screen_rect.bottom
# Store a decimal value for the man's center.
self.center = float(self.rect.centerx)
# Movement flags
self.moving_right = False
self.moving_left = False
self.orientation = False
def update(self):
# Update the man's center value, not the rect
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.man_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.man_speed_factor
# Update rect object from self.center.
self.rect.centerx = self.center
def blitme(self):
# Draw sprite
self.screen.blit(self.image, self.rect)
# Flip sprite depending on right/left key
if self.orientation == "Right":
self.screen.blit(self.image, self.rect)
elif self.orientation == "Left":
self.screen.blit(pygame.transform.flip(self.image, True, False),
self.rect)
game_functions.py
def fire_bullet(ai_settings, bullets, screen, man):
# Fire a bullet as long as max bullets is not reached
# Create a new bullet and add it to the bullets group.
if len(bullets) < ai_settings.bullets_allowed:
fire_sound.play()
new_bullet = Bullet(ai_settings, screen, man)
bullets.add(new_bullet)
这是“更新”之后的相同代码:
man.py
class Man(Sprite):
# --- SNIP ---
# A field to keep track of timeout
self.timeout = 0
def update(self):
# --- SNIP ---
clock = pygame.time.Clock()
dt = clock.tick(60)
if self.timeout > 0:
self.timeout = max(self.timeout - dt, 0)
def blitme(self):
# --- SNIP ---
# Change into firesprite when pressing space
elif self.timeout > 0 and self.orientation == 'Right':
self.screen.blit(self.fire, self.rect)
elif self.timeout > 0 and self.orientation == 'Left':
self.screen.blit(pygame.transform.flip(self.fire, True, False),
self.rect)
game_functions.py
def fire_bullet(ai_settings, bullets, screen, man):
# --- SNIP ---
man.timeout = 80
答案 0 :(得分:0)
tick()
对象的方法 pygame.time.Clock
以这种方式延迟游戏,即循环的每次迭代消耗相同的时间段。见pygame.time.Clock.tick()
:
这个方法应该每帧调用一次。
您需要每帧调用一次 clock.tick(60)
,而不是为每个更新的对象调用一次。如果您有多个对象,则该方法将在每一帧中被调用多次,并且随着对象数量的增加,游戏速度会变慢。