微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Pygame 计算鼠标速度?

如何解决如何使用 Pygame 计算鼠标速度?

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)

您好,我是 Pygame 的新手,现在,我的程序可以跟踪鼠标坐标并创建点击时间。但我想计算鼠标从一次点击到下一次点击的速度(以每秒像素为单位)。

提前致谢。

解决方法

使用 pygame.time.get_ticks() 返回自调用 pygame.init() 以来的毫秒数。
计算 2 次点击之间的 Euclidean distance 并将其除以时间差:

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

    # [...]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。