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

前端 未结 1 1427
广开言路
广开言路 2020-12-12 04:43

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 whic

相关标签:
1条回答
  • 2020-12-12 05:19

    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]
        # [...]
    
    0 讨论(0)
提交回复
热议问题