【发布时间】:2022-11-22 23:54:44
【问题描述】:
我正在尝试在 pygame 中使用鼠标运动移动由磁盘上的图像表示的表面,这是我的代码:
import sys
import pygame
from pygame.locals import *
WINDOW_SIZE = (600, 400)
FPS = 60
class System:
def __init__(self, screen, surface):
self.screen = screen
self.surface = pygame.transform.scale(surface, (WINDOW_SIZE[0] * 2, WINDOW_SIZE[1] * 2))
self.clock = pygame.time.Clock()
def run(self):
running = True
moving = False
offset_x = 0
offset_y = 0
while running:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_SPACE:
mouse_pos = pygame.mouse.get_pos()
if self.surface.get_rect().collidepoint(mouse_pos):
moving = True
elif event.type == pygame.KEYUP:
moving = False
elif event.type == MOUSEMOTION and moving:
offset_x = event.rel[0]
offset_y = event.rel[1]
elif event.type == MOUSEWHEEL:
offset_y -= event.y * 50
self.screen.fill((105, 212, 229))
self.screen.blit(self.surface, (offset_x, offset_y))
pygame.display.update()
self.clock.tick(FPS)
def run_system(screen, surface):
system = System(screen, surface)
system.run()
pygame.init()
screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32)
surface = pygame.image.load('image.png')
if __name__ == '__main__':
run_system(screen, surface)
表面无法正常移动。当我移动鼠标时它会快速摇晃。我正在使用 event.rel 来获得相对运动。也许这不是正确的方法。你有别的方法吗?
附言:我也按空格键激活运动(moving变量)但这不是问题,这工作正常。
【问题讨论】:
标签: python pygame mouse motion