1

我在场景中使用游戏并加载按钮作为图像,当我尝试使用button[0].get_rect()时,单击时收到坐标 0,0 而不是按钮的实际坐标。

我的代码如下

button = []
button.append(pygame.image.load('images/new_game.png').convert_alpha())
button_pos = (700, 100)

并在while使用此代码检查按钮是否被点击

 screen.fill(0)
 screen.blit(button[0], button_pos)
 if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if button[0].get_rect().collidepoint(x, y):
                scene = 2
                print(scene)
4

1 回答 1

1

问题是button.get_rect()返回一个 Rect 来描述图像的位置和尺寸,就好像它位于 (0,0) 处一样。需要告诉它正确的位置坐标在哪里。

代码已经有了button_pos,因此只需将其应用于 Rect ,button[0].get_rect()我们就可以得到一个具有正确位置尺寸的最终 Rect 。然后可以检查此 Rect 和事件提供的鼠标位置之间的冲突。

button_rect = button[0].get_rect()
button_rect.topleft = button_pos       # now the rect matches the on-screen 

# ...

screen.fill( 0 )
screen.blit( button[0], button_rect ) 

if event.type == pygame.MOUSEBUTTONDOWN:
    x, y = event.pos
    if button_rect.collidepoint( x, y ):
        scene = 2
        print( scene )

可能您想制作一个按钮 Rects 列表,并为button列表中的每个图像设置一个,但此示例基于您在问题中提出的内容,因此不这样做。

于 2020-06-29T07:30:20.113 回答