如何在pygame中跟随鼠标移动时检查玩家的方向是否沿x方向改变

问题描述

我正在使用 pygame 创建一个简单的垂直滚动超休闲游戏。在这里,我的播放器跟随鼠标移动并根据鼠标位置更改其位置。现在我想在播放器从左端向右端改变方向时播放哔声,反之亦然。我尝试使用两个布尔值并检查相对运动,但效果不佳。我该怎么做?

enter image description here

这是我检查方向变化的代码

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...