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

妖精的绣舞 提交于 2020-12-21 04:11:28

问题


I'm trying to tell when a sprite, which must be part of a particular group (pygame.sprite.Group()), is clicked on. 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:

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.

When I try this, I am told that "Group has no attribute rect". Where do I go from here?


回答1:


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():

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

The Sprites in a pygame.sprite.Group can iterate through. 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. If the Sprites are not overlapping, then the list will contain 0 or 1 element:

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]
    # [...]


来源:https://stackoverflow.com/questions/58917346/how-to-detect-when-a-rectangular-object-image-or-sprite-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!