【问题标题】:How do I get the Mouse Position on a Pygame Scaled Surface?如何在 Pygame Scaled Surface 上获得鼠标位置?
【发布时间】:2018-10-31 14:20:26
【问题描述】:

我正在制作的游戏将所有内容都传送到 pygame.surface 上,然后将其缩放到用户显示器的大小,保持纵横比,然后将表面传送到主屏幕。我现在遇到的问题是,当我查询鼠标位置时(因为我想对某些精灵做悬停效果),它远离精灵的位置,但 x 和 y 匹配精灵的坐标。这是因为我已经缩放了表面吗?如果是这样,是否有内置的 Pygame 方法可以将鼠标分配到不同的表面?还是我必须编写一个算法来转换坐标?

【问题讨论】:

    标签: python-3.x pygame pygame-surface


    【解决方案1】:

    您也可以通过缩放源表面的因子“缩放”鼠标位置

    这是一个简单的例子

    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 在屏幕的(0, 0) 处被blitted。如果你要在别处使用 blit,你就必须相应地平移鼠标位置。

    【讨论】:

    • 出色的@sloth 这正是我所追求的!让我烦恼的是精灵会亮起,但只有当鼠标向右和向下移动时才会亮起,但位置似乎匹配。然后我想到这可能是因为缩放。幸运的是,我的表面位于 (0, 0),所以这将完美运行,谢谢哥们。
    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多