首页 > 解决方案 > 在受限时跟踪鼠标移动

问题描述

即使鼠标被限制在 200、200 等位置,我也需要能够跟踪鼠标并将其显示在 pygame 窗口中。我的代码是这样的

import pygame
import time
from pygame.locals import *
import pyautogui

pygame.init()

DISPLAY=pygame.display.set_mode((int(2560/3),int(1440/3)),0,32)

WHITE=(255,255,255)
BLUE=(0,0,255)

DISPLAY.fill(WHITE)

w = pyautogui.position()
x_mouse = w.x
y_mouse = w.y
oldx = x_mouse
oldy = y_mouse
div = 3
x = x_mouse/div
y = y_mouse/div

while True:
    DISPLAY.fill(WHITE)
    pygame.draw.rect(DISPLAY,BLUE,(x,y,50,50))
    w = pyautogui.position()
    x_mouse = w.x
    y_mouse = w.y

    if x_mouse > oldx:
        x+=(x_mouse-oldx)/div
    if x_mouse < oldx:
        x-=(oldx-x_mouse)/div

    if y_mouse > oldy:
        y+=(y_mouse-oldy)/div
    if y_mouse < oldy:
        y-=(oldy-y_mouse)/div

    oldx = x_mouse
    oldy = y_mouse
    
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            
    pygame.display.update()

这工作正常,但是当鼠标被限制在一个位置时它会完全中断,有什么办法可以解决这个问题?

标签: pythonpygamemouseeventmousepyautogui

解决方案


我建议使用pygame.mouse模块,pygame.mouse.get_pos()而不是pyautogui ,而不是:

import pygame
from pygame.locals import *
pygame.init()

DISPLAY = pygame.display.set_mode((int(2560/3),int(1440/3)),0,32)
clock = pygame.time.Clock()

WHITE = (255, 255, 255)
BLUE = (0, 0, 255)

x_mouse, y_mouse = pygame.mouse.get_pos()
div = 10
x, y = x_mouse/div, y_mouse/div

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
    
    x_mouse, y_mouse = pygame.mouse.get_pos()
    x += (x_mouse - x) / div
    y += (y_mouse - y) / div
    
    DISPLAY.fill(WHITE)
    rect = pygame.Rect(0, 0, 50, 50)
    rect.center = round(x), round(y)
    pygame.draw.rect(DISPLAY, BLUE, rect)        
    pygame.display.update()

另请参阅如何在 pygame 中进行平滑移动


推荐阅读