how to detect if the sprite has been clicked in pygame

前端 未结 2 622
臣服心动
臣服心动 2021-01-05 03:43

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 l

相关标签:
2条回答
  • 2021-01-05 04:27

    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.

    0 讨论(0)
  • 2021-01-05 04:35

    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:

    • http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide
    • http://www.pygame.org/docs/ref/sprite.html
    • http://www.pygame.org/docs/ref/rect.html
    0 讨论(0)
提交回复
热议问题