我需要放大图像,如果图像检测到鼠标,但我不知道的方式。我认为很难用pygame.mouse.get_pos()和图像的rect来检测它,因为图像是一个圆,而不是一个矩形。虽然鼠标在图像的角落,但它可能检测到鼠标,而不是触摸它。
发布于 2018-10-20 07:13:53
您可以使用毕达哥拉斯定理计算鼠标与圆心之间的距离,也可以只计算math.hypot。如果距离小于半径,鼠标和圆环就会发生碰撞。
另外,为图像创建一个矩形,作为blit的位置,这样就可以很容易地获得中心点。
import math
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
radius = 60 # Circle radius.
IMAGE = pg.Surface((120, 120), pg.SRCALPHA)
pg.draw.circle(IMAGE, (225, 0, 0), (radius, radius), radius)
# Use this rect to position the image.
rect = IMAGE.get_rect(center=(200, 200))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEMOTION:
mouse_pos = event.pos # Or `pg.mouse.get_pos()`.
# Calculate the x and y distances between the mouse and the center.
dist_x = mouse_pos[0] - rect.centerx
dist_y = mouse_pos[1] - rect.centery
# Calculate the length of the hypotenuse. If it's less than the
# radius, the mouse collides with the circle.
if math.hypot(dist_x, dist_y) < radius:
print('collision')
screen.fill(BG_COLOR)
screen.blit(IMAGE, rect)
pg.display.flip()
clock.tick(60)
pg.quit()如果您正在处理精灵,您也可以使用口罩进行像素完美碰撞检测或pygame.sprite.collide_circle。
https://stackoverflow.com/questions/52901809
复制相似问题