限制时跟踪鼠标的移动

时间:2020-10-22 22:22:20

标签: python pygame mouseevent mouse pyautogui

即使鼠标被限制在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()

这可以正常工作,但是当鼠标被限制在某个位置时,它可以完全解决问题,以任何方式解决此问题?

1 个答案:

答案 0 :(得分:0)

我建议使用 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()

另见How to make smooth movement in pygame