问题描述
我是 pygame 的新手,现在我正在使用精灵.我的问题是如何检测精灵是否被点击?我想在精灵被点击时做一些事情,就像一个按钮.
Im new in pygame, right now im working with sprites. My question is how do i detect if the sprite has been clicked? I want to do something when the sprite was clicked just like a button.
谢谢:)
[已编辑]
谢谢斯蒂芬.另外有没有办法知道被点击的精灵是谁?这是示例代码
thx Stephen. In addition is there a way to know who is the sprite that was clicked? Here is sample code
boxes = pygame.sprite.Group()
for color, location in [([255, 0, 0], [0, 0]),
([0, 255, 0], [60, 60]),
([0, 0, 255], [120, 120])]:
boxes.add(UpDownBox(color, location)
例如,我单击位置 [0,0] 中的精灵,程序应打印其颜色或位置.再次感谢:)
for example i click the sprite in location [0,0], the program should print its color or its location. thanks again :)
推荐答案
我已经很久没有在 Pygame 做过任何事情了,但是 IIRC 的基本想法是你的精灵应该有一个 rect
属性.当您收到鼠标点击事件时,您获取位置 通过调用 pygame.mouse.get_pos()
.然后您可以检查rect
通过在两个 rect
对象上调用 pygame.sprite.collide_rect()
以鼠标位置和精灵的 rect 为中心.
A good example can be found here.
这篇关于如何检测精灵是否在pygame中被点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!