如何检测精灵是否在pygame中被点击 [英] how to detect if the sprite has been clicked in pygame

查看:97
本文介绍了如何检测精灵是否在pygame中被点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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 <描述其在屏幕上的位置的 href="http://www.pygame.org/docs/ref/rect.html" rel="noreferrer">属性.当您收到鼠标点击事件时,您获取位置 通过调用 pygame.mouse.get_pos().然后您可以检查rect 通过在两个 rect 对象上调用 pygame.sprite.collide_rect() 以鼠标位置和精灵的 rect 为中心.

It's been a long time since I did anything in Pygame, but IIRC the basic idea is that your sprite should have a rect attribute that describes its position on the screen. When you receive a mouse click event, you get the position by calling pygame.mouse.get_pos(). You can then check for a collision between a rect centered at the mouse position and your sprite's rect by calling pygame.sprite.collide_rect() on both rect objects.

可以在此处找到一个很好的例子.

A good example can be found here.

这篇关于如何检测精灵是否在pygame中被点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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