如何检测单击矩形对象,图像或精灵的时间 [英] How to detect when a rectangular object, image or sprite is clicked

查看:45
本文介绍了如何检测单击矩形对象,图像或精灵的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道何时单击一个精灵,该精灵必须是特定组( pygame.sprite.Group())的一部分.目前,我已经尝试创建一个仅在鼠标位置完全不可见的精灵,将其添加到其自己的组中,并使用以下代码:

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)

其中 guess1 是被单击的精灵,而 mice 是包含具有鼠标位置的精灵的组.

where guess1 is the sprite getting clicked on and mice is the group containing the sprite that has the position of the mouse.

尝试此操作时,系统会告诉我组没有属性rect".我从这里去哪里?

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

推荐答案

如果您有一个精灵( my_sprite ),并且想验证鼠标是否在精灵上,那么您已经以获得 pygame的 .rect 属性.sprite.Sprite 对象,并通过 .collidepoint():

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

pygame.sprite中的Sprites.组 可以迭代.因此,测试可以循环执行:

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

或获取鼠标所在的组"中的精灵"列表.如果Sprite不重叠,则列表将包含0或1个元素:

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

这篇关于如何检测单击矩形对象,图像或精灵的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆