问题描述
在我的游戏中,玩家可以使用WASD键发射不同颜色的子弹。播放器可以立即发射子弹,就像他们现在按下键一样快,这意味着您可以将WASD键混在一起并发射子弹流。我曾尝试创建一个USEREVENT来冷却玩家可以射击的时间,但是我不确定自己是否做对了,因为我在玩游戏时根本不射击。
#cooldown userevent
shot_cool = pygame.USEREVENT + 2
pygame.time.set_timer(shot_cool,10)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False #breaks out of the while loop
if event.type == pygame.KEYDOWN and event.type == shot_cool:
if event.key == pygame.K_w:
pygame.time.set_timer(shot_cool,10)
player.shoot('red')
elif event.key == pygame.K_a:
pygame.time.set_timer(shot_cool,10)
player.shoot('green')
elif event.key == pygame.K_s:
pygame.time.set_timer(shot_cool,10)
player.shoot('white')
elif event.key == pygame.K_d:
pygame.time.set_timer(shot_cool,10)
player.shoot('blue')
有什么办法可以使玩家有短暂的冷却时间,直到他可以发射另一枚子弹?
解决方法
正如我在评论中所说,您完美地解决了您的问题。但是由于我已经在编辑器中拥有它,所以我决定再分享一点。由于所有按键的功能相同,因此您可以使用字典在同一功能块中对其进行处理。最终可能看起来像这样:
#cooldown userevent
EVT_SHOT_COOLDOWN = pygame.USEREVENT + 2
# shot cool down time
COOLDOWN_TIME_MS = 100
SHOT_KEYS = {
pygame.K_w:'red',pygame.K_a:'green',pygame.K_s:'white',pygame.K_d:'blue',}
running = True
shot_delay = False
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False #breaks out of the while loop
elif event_type == shot_cool:
shot_delay = False
elif event.type == pygame.KEYDOWN:
# handle shooting keys
if (event.key in SHOT_KEYS and not shot_delay):
pygame.time.set_timer(shot_cool,COOLDOWN_TIME_MS)
shot_delay = True
player.shoot(SHOT_KEYS[event.key])
# handle other keys (if any)
,
感谢RufusVS的评论,您说的很完美。这是工作代码:
shoot_cooldown = pygame.USEREVENT +2
pygame.time.set_timer(shoot_cooldown,100)
shot_delay = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == shoot_cooldown:
shot_delay = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w and shot_delay == False:
pygame.time.set_timer(shoot_cooldown,100)
shot_delay = True
player.shoot('red')
elif event.key == pygame.K_a and shot_delay == False:
pygame.time.set_timer(shoot_cooldown,100)
shot_delay = True
player.shoot('green')
elif event.key == pygame.K_s and shot_delay == False:
pygame.time.set_timer(shoot_cooldown,100)
shot_delay = True
player.shoot('white')
elif event.key == pygame.K_d and shot_delay == False:
pygame.time.set_timer(shoot_cooldown,100)
shot_delay = True
player.shoot('blue')