Pygame 鼠标悬停检测

我有确定鼠标光标是否在对象上的代码。但问题是它会向控制台输出大量打印内容。我如何确保如果光标在一个对象上,它会打印一次?


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 的定义。我从那里移走了它,现在一切正常,非常感谢大家


慕桂英4014372
浏览 120回答 2
2回答

阿波罗的战车

这听起来可能有点初级,但是您是否尝试过添加标志?你已经有了一个带有 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 就充当了一个标志,只允许 print 语句运行一次并更改 image.fill 一次。只需去掉一个缩进,就可以将 Image.fill 更改为每次运行。虽然,我不确定您使用 mouse_over 的目的是什么,因此您可能决定创建一个新标志。它仍然需要检查和更改,就像 mouse_over 在这里一样,只是使用不同的变量名。

四季花海

只需使用另一个 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python