How can i calculate the mouse speed with Pygame?

Viewed 104
import pygame
import datetime
with open('textdatei.txt', 'a') as file:

    pygame.init()
    print("Start: " + str(datetime.datetime.now()), file=file)

    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    BG_COLOR = pygame.Color('gray12')

    done = False
    while not done:
        # This event loop empties the event queue each frame.
        for event in pygame.event.get():
            # Quit by pressing the X button of the window.
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # MOUSEBUTTONDOWN events have a pos and a button attribute
                # which you can use as well. This will be printed once per
                # event / mouse click.
                print('In the event loop:', event.pos, event.button)
                print("Maus wurde geklickt: " + str(datetime.datetime.now()), file=file)


        # Instead of the event loop above you could also call pygame.event.pump
        # each frame to prevent the window from freezing. Comment it out to check it.
        # pygame.event.pump()

        click = pygame.mouse.get_pressed()
        mousex, mousey = pygame.mouse.get_pos()
        print(click, mousex, mousey, file=file)

        screen.fill(BG_COLOR)
        pygame.display.flip()
        clock.tick(60)  # Limit the frame rate to 60 FPS.
    print("Ende: " + str(datetime.datetime.now()), file=file)

Hello, I am new in Pygame and for now, my Programm can track the mouse coordinates and it creates the time of the click. But i want to calculate the Speed of the Mouse from one click to the next click (in Pixels per Second).

Thanks in advance.

1 Answers

Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called.
Compute the Euclidean distance between 2 clicks and divide it by the time difference:

import math
prev_time = 0
prev_pos = (0, 0)
click_count = 0

done = False
while not done:
    # This event loop empties the event queue each frame.
    for event in pygame.event.get():
        # Quit by pressing the X button of the window.
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
            
            act_time = pygame.time.get_ticks() # milliseconds
            act_pos = event.pos

            if click_count > 0:
                dt = act_time - prev_time 
                dist = math.hypot(act_pos[0] - prev_pos[0], act_pos[1] - prev_pos[1]) 

                speed = 1000 * dist / dt # pixle / seconds
                print(speed, "pixel/second")

            prev_time = act_time
            prev_pos = act_pos
            click_count += 1

    # [...]
Related