svs
svs

Reputation: 441

how to check mousemotion in an undefined direction in pygame?

I want to check if the mouse has moved following an undefined direction like so:

for event in pygame.event.get():
    if event.type == pygame.MOUSEMOTION:
        "do something"

then I want to print the direction. Is that possible?

Upvotes: 1

Views: 278

Answers (2)

jchanger
jchanger

Reputation: 738

Another possibility would be pygame.mouse.get_rel() which provides the amount of movement of the mouse since the last call to this function. This way you can avoid storing the previous position.

Simple example:

import sys, pygame,time

FPS=30
fpsClock=pygame.time.Clock()

screen = pygame.display.set_mode((650,650))
screen.fill(255,255,255)
done = False 

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEMOTION:
            print pygame.mouse.get_rel()

    pygame.display.update()
    fpsClock.tick(FPS)

You will get an output like the one shown below and, as you can see, you can interpret it as vectors in the form (x,y) describing the direction of the movement:

(0, 0)
(-1, 0) 
(0, -8)
(0, 0)

Upvotes: 1

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11190

You are halfway there:

An event with type pygame.MOUSEMOTION event has a pos member. You can store the previous pos, and calculate the difference - direction.

Upvotes: 1

Related Questions