(Pygame)鼠标悬停检测问题

2024-10-02 14:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经看到了theseposts,但仍然没有鼠标覆盖检测工作。我正在为一个朋友开发一个简单的游戏开始菜单;有两段文字,当鼠标悬停在上面时它们应该变成蓝色。你知道吗

但是,只有当我将鼠标悬停在左上角时,它们才会变成蓝色:我假设我的代码正在检测位于左上角的原始(未放置和未定位)曲面,并将转换为矩形,然后检查.collidepoint(pygame.mouse.get\位置()). 你知道吗

我如何使它检测到已blits和定位文本?你知道吗

下面是我的代码(或者至少是引起麻烦的部分):

font = pygame.font.Font(os.path.join('.', 'bin', 'NOVEMBER.TTF'), 26)
playText = font.render("Play", True, lightGray)
settingsText = font.render("Options", True, lightGray)
setDisplay.fill(darkGray)
playText_rect = playText.get_rect()
settingsText_rect = settingsText.get_rect()

然后,在我的主循环中:

if settingsText_rect.collidepoint(pygame.mouse.get_pos()):
        settingsText = font.render("Options", True, grayBlue)
        setDisplay.blit(settingsText, (rightBorder / 2 - settingsText.get_width() / 2 + 200, bottomBorder / 2 - settingsText.get_height() / 2 + 120))
    elif playText_rect.collidepoint(pygame.mouse.get_pos()):
        playText = font.render("Play", True, grayBlue)
        setDisplay.blit(playText, (rightBorder / 2 - playText.get_width() / 2 - 200, bottomBorder / 2 - playText.get_height() / 2 + 120))
    else:
        playText = font.render("Play", True, lightGray)
        settingsText = font.render("Options", True, lightGray)

哦,如果有什么不同的话,我会上Ubuntu的。你知道吗


Tags: recttrueplaygetrenderpygame蓝色options
1条回答
网友
1楼 · 发布于 2024-10-02 14:30:47

当您在Surface上调用.get_rect()时,结果Rect确实将其xy位置设置为0。你知道吗

解决这个问题的一个简单方法是使用playText_rectsettingsText_rect进行blitting,而不是计算主循环中的位置。你知道吗

# calculate the position once and but the rect at that position
playText_rect = playText.get_rect(topleft=(rightBorder / 2 - playText.get_width() / 2 - 200, bottomBorder / 2 - playText.get_height() / 2 + 120))
settingsText_rect = settingsText.get_rect(topleft=(rightBorder / 2 - settingsText.get_width() / 2 + 200, bottomBorder / 2 - settingsText.get_height() / 2 + 120))

...

# use the rect as position argument for blit
setDisplay.blit(settingsText, settingsText_rect)

...

setDisplay.blit(playText, playText_rect)

相关问题 更多 >