Prajjwal Pathak
Prajjwal Pathak

Reputation: 119

How to check if player's direction changed in x direction while following mouse motion in pygame

I'm creating a simple vertical scroller hyper casual game using pygame. Here my player follows the mouse motion and changes it's location based on mouse position. Now I want to play a beep sound whenever the player changes it's direction from left end towards right or vice-versa. I tried using two Boolean and checking relative movement but it's not working well. How can I do it ?

enter image description here

Here's my code to check for direction change

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

Upvotes: 2

Views: 340

Answers (1)

Matteo
Matteo

Reputation: 66

Make a variable outside the game loop where you store the current x position, so that the next loop you can see if the new x position is higher (right) or lower (left) than the previous one, like:

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

Upvotes: 1

Related Questions