我正在制作的游戏将所有内容都绘制在一个pygame.surface上,然后将其缩放到用户显示器的大小,保持长宽比不变,然后再将表面绘制到主屏幕上。我现在遇到的问题是,当我查询鼠标位置(因为我想在某些精灵上实现悬停效果)时,它的位置偏离精灵的位置很远,但x和y与精灵的坐标相匹配。这是因为我缩放了表面吗?如果是这样的话,是否有Pygame内置方法可以将鼠标分配给不同的表面?或者我需要编写一个转换坐标的算法?
import string
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
screen_rect = screen.get_rect()
clock = pg.time.Clock()
# the surface we draw our stuff on
some_surface = pg.Surface((320, 240))
some_surface_rect = some_surface.get_rect()
# just something we want to check for mouse hovering
click_me = pg.Surface((100, 100))
click_me_rect = click_me.get_rect(center=(100, 100))
hover = False
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT or event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
done = True
# draw some stuff on our surface
some_surface.fill(pg.Color('gray12'))
click_me.fill(pg.Color('dodgerblue') if not hover else pg.Color('red'))
some_surface.blit(click_me, click_me_rect)
# scale it
scaled_surface = pg.transform.scale(some_surface, screen_rect.size)
# draw it on the window
screen.blit(scaled_surface, (0, 0))
pos = list(pg.mouse.get_pos())
# take the mouse position and scale it, too
ratio_x = (screen_rect.width / some_surface_rect.width)
ratio_y = (screen_rect.height / some_surface_rect.height)
scaled_pos = (pos[0] / ratio_x, pos[1] / ratio_y)
# use collidepoint as usual
hover = click_me_rect.collidepoint(scaled_pos)
pg.display.flip()
clock.tick(60)
pg.quit()
当然,这只有在将 scaled_surface
blit到屏幕的 (0, 0)
时才有效。如果你想要在其他地方blit它,你需要相应地翻译鼠标位置。