这是我的代码的一部分,问题在于:
button = pygame.image.load("button1.png")
screen.blit(button, (100, 100))
这张图片看起来像这样:
[
当用户点击图片时,我需要增加一个变量的值。
我尝试了一些解决方案,但大多数解决方案都是在图片上绘制一个“不可见”的矩形,即使有人点击三角形附近的空白区域,变量的值也会增加。
最佳答案
使用 mask
module 非常简单.
来自文档:
Useful for fast pixel perfect collision detection. A mask uses 1 bit per-pixel to store which parts collide.
首先,创建一个 Mask
从图像
mask = pygame.mask.from_surface(button)
然后,在检查鼠标点击事件时,检查掩码中的点是否为set。 .
这是一个简单的例子:
import pygame
def main():
pygame.init()
screen = pygame.display.set_mode((480, 320))
button = pygame.image.load('button.png').convert_alpha()
button_pos = (100, 100)
mask = pygame.mask.from_surface(button)
x = 0
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
return
if e.type == pygame.MOUSEBUTTONDOWN:
try:
if mask.get_at((e.pos[0]-button_pos[0], e.pos[1]-button_pos[1])):
x += 1
print(x)
except IndexError:
pass
screen.fill((80,80,80))
screen.blit(button, button_pos)
pygame.display.flip()
main()
用于测试的示例 button.png:
关于python - Pygame 点击图像(不是矩形),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56562371/