Pygame 鼠标悬停检测

Pygame mouse over detect

我有代码可以确定鼠标光标是否在某个对象上。但问题是它向控制台输出了很多打印。我如何确保如果光标在某个对象上,它会打印一次?

if player.rect.collidepoint(pygame.mouse.get_pos()):
    mouse_over = True
    print(True)
    player.image.fill(RED)
else:
    mouse_over = False
    print(False)
    player.image.fill(GREEN)

我看起来很傻。我在循环中定义了变量 mouse_over = 0 。我把它从那里移走了,现在一切正常了,非常感谢大家

只需使用另一个 if 语句来查看它是否已经在 rect 中。并且不要打印出来。

if player.rect.collidepoint(pygame.mouse.get_pos()):
    if not mouse_over:
        print(True)
    mouse_over = True
    player.image.fill(RED)
else:
    mouse_over = False
    player.image.fill(GREEN)

这听起来可能有点初级,但您尝试过添加标志吗?你已经有一个带有 mouse_over 的布尔值,所以对我来说有这样的东西很有意义:

if player.rect,collidepoint(pygame.mouse.get_pos()):
    if(mouse_over==False):
        mouse_over=True
        print(True)
        player.image.fill(RED)
else:
    if(mouse_over==True):
        mouse_over=False
        print(False)
        player.image.fill(GREEN)

这样,mouse_over作为标志,只允许打印语句运行一次,改变image.fill一次。 Image.fill 每次都可以更改为 运行 只需去掉一个缩进即可。

不过,我不确定您 mouse_over 的用途,因此您可能决定创建一个新标志。它仍然需要像 mouse_over 一样进行检查和更改,只是使用不同的变量名称。