简体   繁体   English

如何检测何时单击矩形 object、图像或精灵

[英]How to detect when a rectangular object, image or sprite is clicked

I'm trying to tell when a sprite, which must be part of a particular group ( pygame.sprite.Group() ), is clicked on.我试图判断何时单击必须属于特定组( pygame.sprite.Group() )的精灵。 Currently I've tried creating a sprite which is just the mouses position and totally invisible, adding it to its own group, and using this code:目前我已经尝试创建一个精灵,它只是鼠标 position 并且完全不可见,将其添加到自己的组中,并使用以下代码:

clickedList = pygame.sprite.spritecollide(guess1, mice, False)

where guess1 is the sprite getting clicked on and mice is the group containing the sprite that has the position of the mouse.其中guess1是被点击的精灵, mice是包含具有鼠标position的精灵的组。

When I try this, I am told that "Group has no attribute rect".当我尝试这个时,我被告知“组没有属性 rect”。 Where do I go from here?我在哪里 go 从这里?

If you've a sprite ( my_sprite ) and you want to verify if the mouse is on the sprite, then you've to get the .rect attribute of the pygame.sprite.Sprite object and to test if the mouse is in the rectangular area by .collidepoint() :如果您有一个精灵( my_sprite )并且您想验证鼠标是否在精灵上,那么您必须获取pygame.sprite.Sprite object 的.rect属性并测试鼠标是否在矩形中.collidepoint()的面积:

mouse_pos = pygame.mouse.get_pos()
if my_sprite.rect.collidepoint(mouse_pos):
    # [...]

The Sprites in apygame.sprite.Group can iterate through. pygame.sprite.Group中的 Sprite 可以迭代。 So the test can be done in a loop:所以测试可以循环进行:

mouse_pos = pygame.mouse.get_pos()
for sprite in mice:
    if sprite.rect.collidepoint(mouse_pos):
        # [...]

Or get a list of the Sprites within the Group, where the mouse is on it.或者获取组内的 Sprite 列表,鼠标所在的位置。 If the Sprites are not overlapping, then the list will contain 0 or 1 element:如果 Sprite 不重叠,则列表将包含 0 或 1 个元素:

mouse_pos = pygame.mouse.get_pos()
clicked_list = [sprite for sprite in mice if sprite.rect.collidepoint(mouse_pos)]

if any(clicked_list):
    clicked_sprite = clicked_list[0]
    # [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM