我正在做一个收集精灵的游戏,我收集精灵,然后计算分数。如果我撞到墙上,它会发出撞墙的声音。当我撞到墙上时,我只希望声音播放一次,然后避免播放,直到再次满足要求。这是我的代码与声音碰撞的墙壁。
def wallCollide():
if player.rect.x == 1 and player.rect.y < 479:
bumpWall.play()
if player.rect.y == 1 and player.rect.x < 479:
bumpWall.play()
if player.rect.x == 478 and player.rect.y < 479:
bumpWall.play()
if player.rect.y == 478 and player.rect.x < 479:
bumpWall.play()
问题来源StackOverflow 地址:/questions/59386358/how-to-make-a-pygame-sound-only-play-once-then-stop-until-the-requirements-are
快速的方法是在玩家撞到墙的同一帧将玩家移动(传送)到离墙2~5个像素的地方。 但如果你想让玩家呆在墙内或滑向墙附近,那么你需要更强大的解决方案。使用状态机:
PL_STATE_WITHIN_BOUNDS = 1
PL_STATE_JUST_HIT_THE_WALL = 2
PL_STATE_COLLIDING_WITH_THE_WALL = 3
def calc_next_player_state(player, pl_state):
# Convert your `wallCollide` to return bool:
# - False when within bounds
# - True when colliding with the wall
if is_colliding_with_the_wall(player):
if pl_state == PL_STATE_WITHIN_BOUNDS:
return PL_STATE_JUST_HIT_THE_WALL
else:
return PL_STATE_COLLIDING_WITH_THE_WALL
else:
return PL_STATE_WITHIN_BOUNDS
pl_state = PL_STATE_WITHIN_BOUNDS
while True: # Game's main loop
# ...
pl_state = calc_next_player_state(player, pl_state)
if pl_state == PL_STATE_JUST_HIT_THE_WALL:
bump_wall.play()
# ...
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。