pygame鼠标速度

问题描述

我是编码和pygame的新手,我正在寻找代码来检查鼠标是否以特定速度移动。如果是这样,则退出游戏。

if the mouse speed is greater than say 10 pixels per second
     Run = False

解决方法

MOUSEMOTION事件具有属性rel,该属性表示鼠标相对于其先前位置已移动了多少。使用此属性,我们可以使用毕达哥拉斯定理(**表示Python中的幂)来计算速度。因此,在事件循环中,您可以执行以下操作:

for event in pygame.event.get():
    if event.type == pygame.MOUSEMOTION:
        dx,dy = event.rel
        speed = (dx ** 2 + dy ** 2) ** (1/2)  # Pythagoras theorem.
        if speed >= MAX_SPEED:
            quit()  # Or show quit screen or whatever.

确保在循环之前定义MAX_SPEED(例如,作为全局变量)。

此方法的一个问题是,第一个事件将具有与原点的相对位置,即,如果在游戏开始时鼠标位于(100,100),则rel属性将是(100,100 )。

由于您可能不希望在应用程序开始时立即执行游戏规则,因此这不成问题。但是,如果您想在执行此规则的情况下打开游戏,则需要跳过第一个MOUSEMOTION事件。这可以通过检查布尔值来完成。

# Define this globally (or somewhere where it will only be set on startup).
# Also,use a better name than 'first'. Something that represent the logic for your game. 
first = False


for event in pygame.event.get():
    if event.type == pygame.MOUSEMOTION:
        dx,dy = event.rel
        speed = (dx ** 2 + dy ** 2) ** (1/2)  # Pythagoras theorem.
        if speed >= MAX_SPEED and first:
            quit()  # Or show quit screen or whatever.
        first = True
,

每帧都可以通过pygame.mouse.get_pos()函数跟踪鼠标的位置,当鼠标改变时,请检查pygame.time.get_ticks()的时间。

类似的东西:

MAX_SPEED = 50

previous_mouse_position = None
previous_sample_time    = None
...

current_mouse_pos = pygame.mouse.get_pos()
if ( previous_mouse_position != current_mouse_pos ):
    # mouse has moved
    pixels_movement = distance( previous_mouse_position,current_mouse_pos )
    time_now        = pygame.time.get_ticks()
    movement_time   = ( time_now - previous_sample_time ) / 1000  # milliseconds -> seconds
    movement_speed = pixels_movement / movement_time
    if ( movement_speed > MAX_SPEED ):
        doSomething()

elif ( previous_mouse_position == None ):
    # No previous recorded position
    previous_mouse_position = current_mouse_pos
    previous_sample_time    = pygame.time.get_ticks()

当然可以很容易地计算出euclidian distance between two points

编辑:

import math

def distance( point1,point2 ):
    """ Return the Euclidian distance between two points 
        Ref: https://en.wikipedia.org/wiki/Euclidean_distance#Two_dimensions """
    # NOTE: this code hasn't been tested
    p1x,p1y  = point1
    p2x,p2y  = point2
    x_squared = ( p2x - p1x ) * ( p2x - p1x )
    y_squared = ( p2y - p1y ) * ( p2y - p1y )
    pixel_dist= math.sqrt( x_squared + y_squared )
    return pixel_dist