简体   繁体   中英

how to detect if the sprite has been clicked in 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 :)

[Edited]

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)

for example i click the sprite in location [0,0], the program should print its color or its location. thanks again :)

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 .

Simpler: Rect.collidepoint(x,y)

main loop

#in event handling:
if event.type == MOUSEMOTION: x,y = event.pos

for box in boxes:
    if box.rect.collidepoint(x,y): print 'yay!'

There are several more collision functions in both Rect and Sprite . See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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