【问题标题】:Pygame action when mouse 'click' on .rect?鼠标在.rect上“单击”时的Pygame动作?
【发布时间】:2012-08-27 23:34:22
【问题描述】:

我一直在编写一个测试函数来了解鼠标在 pygame.rect 上的“点击”动作将如何产生响应。

到目前为止:

def test():
    pygame.init()
    screen = pygame.display.set_mode((770,430))
    pygame.mouse.set_visible(1)
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250,250,250))
    screen.blit(background, (0,0))
    pygame.display.flip()

    ## set-up screen in these lines above ##

    button = pygame.image.load('Pictures/cards/stand.png').convert_alpha()
    screen.blit(button,(300,200))
    pygame.display.flip()

    ## does button need to be 'pygame.sprite.Sprite for this? ##
    ## I use 'get_rect() ##
    button = button.get_rect()

    ## loop to check for mouse action and its position ##
    while True:
        for event in pygame.event.get():
            if event.type == pygame.mouse.get_pressed():
                ## if mouse is pressed get position of cursor ##
                pos = pygame.mouse.get_pos()
                ## check if cursor is on button ##
                if button.collidepoint(pos):
                    ## exit ##
                    return

我在 google 上遇到过人们正在使用或建议对图像使用 pygame.sprite.Sprite 类的页面,我认为这就是我的问题所在。我已经检查了 pygames 文档,并且方法之间没有太大的凝聚力,恕我直言。我显然遗漏了一些简单的东西,但是我认为get_rect 会让 pygames 中的图像能够检查按下时鼠标位置是否在它上面?

编辑: 我想我需要调用pygame.sprite.Sprite 方法来使图像/矩形具有交互性?

【问题讨论】:

    标签: python mouseevent pygame rect


    【解决方案1】:

    好吧,如果有人感兴趣或遇到类似问题,这就是我需要更改的地方。

    首先,删除:

    button = button.get_rect()
    

    然后:

    screen.blit(button, (300, 200))
    

    应该是:

    b = screen.blit(button, (300, 200))
    

    这将在屏幕上按钮所在区域创建Rect

    到:

    if event.type == pygame.mouse.get_pressed()
    

    我改成:

    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
    

    pygame.mouse.get_pressed() 获取所有三个鼠标按钮(MOUSEBUTTONDOWN、MOUSEBUTTONUP 或 MOUSEMOTION)的状态。我还需要添加 event.button == 1 以指定这是按下的“鼠标左键”按钮。

    最后:

    `if button.collidepoint(pos):` 
    

    到:

    `if b.collidepoint(pos):`
    

    使用Rectb的碰撞点法

    【讨论】:

      【解决方案2】:

      我认为rect方法调用collidepoint,而不是collide*r*point。 这是文档的link

      【讨论】:

      • 很好,我很可能将collide*r*ectcollidepoint 混合在一起。我进行了编辑以显示这一点,但是,我认为您本可以发表评论而不是将此作为答案:P
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 2021-09-06
      相关资源
      最近更新 更多