【发布时间】:2019-10-12 07:00:45
【问题描述】:
好的,所以我有一个用 pygame 制作的游戏。游戏是在屏幕底部有一个人从屏幕顶部向上射击以击中敌人。这个人可以左右移动。
要射你按空格键。
当你射击时,我希望在枪管末端出现一个小精灵,这样看起来就好像火焰像真正的枪击一样冒出来。
我已经设法让火精灵在按下空格键时出现,但我也希望精灵在 0.3 秒后消失(一旦我让它消失,我会调整时间)。
我该怎么做呢?我感觉有点迷失在这里
我尝试用谷歌搜索并查看stackoverflow,但找不到我需要的。
游戏.py
# -- SNIP --
def run_game():
# -- SNIP ---
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
gf.check_events(ai_settings, screen, stats, sb, play_button, man,
enemies, bullets)
if stats.game_active:
man.update()
gf.update_bullets(ai_settings, screen, stats, sb, man, enemies,
bullets)
gf.update_enemies(ai_settings, stats, screen, sb, man, enemies,
bullets)
gf.update_screen(ai_settings, screen, stats, sb, man, enemies,
bullets, play_button)
run_game()
game_functions.py
# -- SNIP --
def check_events(ai_settings, screen, stats, sb, play_button, man, enemies,
bullets):
"""Respond to keypresses and mouse events."""
# -- SNIP --
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, stats, sb, man,
enemies, bullets)
# -- SNIP --
def check_keydown_events(event, ai_settings, screen, stats, sb, man, enemies, bullets):
"""Respond to key presses."""
if event.key == pygame.K_RIGHT:
man.moving_right = True
man.orientation = "Right"
elif event.key == pygame.K_LEFT:
man.moving_left = True
man.orientation = "Left"
# Draw sprite if space is pressed
elif event.key == pygame.K_SPACE:
fire_bullet(ai_settings, bullets, screen, man)
man.fire_screen.blit(man.fire, man.fire_rect)
# --- SNIP ---
# -- SNIP --
man.py
class Man(Sprite):
# -- SNIP --
# Load the man image 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()
# Gun fire sprite
self.fire = pygame.image.load('images/fire.bmp')
self.fire_rect = self.fire.get_rect()
self.screen_fire_rect = self.image.get_rect()
self.fire_screen = self.image
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
# Load the fire sprite at the end of the mans gunbarrel
self.fire_rect.centerx = self.screen_fire_rect.left + 20
self.fire_rect.top = self.screen_fire_rect.top
# ---SNIP---
# Movement flags
self.moving_right = False
self.moving_left = False
self.orientation = False
def blitme(self):
"""Draw the man at its current location."""
self.screen.blit(self.image, self.rect)
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)
【问题讨论】:
-
你想一次发射多发子弹,每发子弹一定时间后“消失”吗?
-
我有它,所以我现在可以“一次”发射 3 发子弹。我可以发射 3 颗子弹,当其中一颗子弹击中敌人或离开屏幕时,我可以射击下一颗子弹,长话短说,我只能同时在屏幕上拥有 3 颗子弹。
-
但我想要的是当我按下空格键时会显示 X 时间的精灵
-
似乎真的很好的方法是使用
pygame.time.set_timer()来导致指定的pygame.USEREVENT在指示时间段已过的所需延迟之后生成。然后,您可以在主事件处理循环中检查此事件并让精灵消失。
标签: python image pygame sprite