问题描述
我正在使用 pygame 创建一个简单的垂直滚动超休闲游戏。在这里,我的播放器跟随鼠标移动并根据鼠标位置更改其位置。现在我想在播放器从左端向右端改变方向时播放哔声,反之亦然。我尝试使用两个布尔值并检查相对运动,但效果不佳。我该怎么做?
这是我检查方向变化的代码
if event.type == pygame.MOUSEBUTTONDOWN and not home_page:
if p.rect.collidepoint(event.pos):
touched = True
x,y = event.pos
offset_x = p.rect.x - x
if event.type == pygame.MOUSEBUTTONUP and not home_page:
touched = False
if event.type == pygame.MOUSEMOTION and not home_page:
if touched:
x,y = event.pos
rel = event.rel[0]
if move_right and rel < -3:
move_right = False
move_left = True
move_fx.play()
if move_left and rel > 3:
move_right = True
move_left = False
move_fx.play()
p.rect.x = x + offset_x
解决方法
在存储当前 x 位置的游戏循环外创建一个变量,以便在下一个循环中您可以查看新的 x 位置是否高于(右侧)或低于(左侧),例如:>
prevx = 0
right = True
left = False
while True:
...
if event.type == pygame.MOUSEMOTION and not home_page:
if touched:
x,y = event.pos
if right and prevx > x: #changed direction to left
right = False
left = True
move_fx.play()
if left and prevx < x: #changed direction to right
right = True
left = False
move_fx.play()
prevx = x
p.rect.x = x + offset_x