如何在 pygame 中检查未定义方向的鼠标移动?

how to check mousemotion in an undefined direction in pygame?

我想检查鼠标是否按照未定义的方向移动,如下所示:

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

那我要打印方向。这可能吗?

你已经完成一半了:

类型为 pygame.MOUSEMOTION 的事件有一个 pos 成员。 可以存储之前的pos,计算差值-方向。

另一种可能是 pygame.mouse.get_rel(),它提供自上次调用此函数以来鼠标的移动量。这样就可以避免存储之前的位置。

简单示例:

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)

您将得到如下所示的输出,如您所见,您可以将其解释为 (x,y) 形式的向量,描述运动:

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