为了账号安全,请及时绑定邮箱和手机立即绑定

Pygame 鼠标悬停检测

Pygame 鼠标悬停检测

慕桂英4014372 2022-10-11 10:17:45
我有确定鼠标光标是否在对象上的代码。但问题是它会向控制台输出大量打印内容。我如何确保如果光标在一个对象上,它会打印一次?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 的定义。我从那里移走了它,现在一切正常,非常感谢大家
查看完整描述

2 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

这听起来可能有点初级,但是您是否尝试过添加标志?你已经有了一个带有 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 在这里一样,只是使用不同的变量名。


查看完整回答
反对 回复 2022-10-11
?
四季花海

TA贡献1811条经验 获得超5个赞

只需使用另一个 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)


查看完整回答
反对 回复 2022-10-11
  • 2 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号