【问题标题】:Track Mouse Movement while confined在受限时跟踪鼠标移动
【发布时间】:2021-02-06 00:10:52
【问题描述】:

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

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

【问题讨论】:

  • 你能解释一下鼠标被“限制在一个位置”是什么意思吗?它是一些操作系统功能吗?或者像“不在pygame窗口中”之类的?
  • 所以基本上这意味着鼠标是不可见的,并且被限制在像200、200这样的位置
  • PyGame 仅在鼠标位于 PyGame 窗口内时接收鼠标移动事件。
  • 不,我使用 pygame 只是为了显示矩形
  • 你想达到什么目的?为什么你使用 pyautogui 而不是 pygame.mouse 模块(例如 pygame.mouse.get_pos)?

标签: python pygame mouseevent mouse pyautogui


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 2022-06-22
    • 2011-07-24
    • 2019-09-04
    • 1970-01-01
    • 2021-12-10
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多