将鼠标锁定在Pygame窗口中

5

我希望在Pygame中制作一个窗口模式下的FPS游戏。

我需要能够自由地移动摄像机360度以上,同时隐藏光标。

我尝试使用Pygame的set_visibleset_pos函数,但这并不能防止鼠标超出窗口并卡在屏幕边缘。

import pygame
pygame.init()
game_display = pygame.display.set_mode((800,600))
pygame.mouse.set_visible(False)

exit = False

while (not exit):
    pygame.mouse.set_pos = (400, 300)
    mouse_move = (0,0)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = True
        if event.type == pygame.MOUSEMOTION:
            mouse_move = event.rel 
    if mouse_move != (0,0):
        print(mouse_move)

pygame.quit()

顺便说一句:set_pos 是一个方法,不是变量—— pygame.mouse.set_pos((400, 300)) 并且它会保持鼠标在内部。 - furas
1个回答

11

你还需要调用pygame.event.set_grab(True)

最好允许用户使用Esc或其他键退出,因为他们将无法再点击x按钮来关闭窗口。

elif event.type == pygame.KEYDOWN:
    if event.key == pygame.K_ESCAPE:
        exit = True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接