【问题标题】:Pygame - Transform screen on mouse movementPygame - 鼠标移动时变换屏幕
【发布时间】:2020-11-26 05:51:06
【问题描述】:

我正在尝试实现转换,如果您按住鼠标左键并移动鼠标,屏幕将相应地转换。与Google maps 中发生的事情相同,即按住并拖动屏幕的事情。我在 pygame 中找不到转换屏幕的函数,例如 screen.transform,所以我这样做了。

我正在从像素转换为笛卡尔坐标,反之亦然。

x_offset = 0
y_offset = 0

# Cartesian to pixels
def to_pixels(x, y):
    center_x = (WIDTH / 2) + x_offset  # The center of the screen (Width/2) + some transformation in x 
    center_y = (HEIGHT / 2) + y_offset 
    return center_x + x, center_y - y

# Pixels to cartesian
def to_cartesian(pW, pH):
    center_x = (WIDTH / 2) + x_offset
    center_y = (HEIGHT / 2) + y_offset
    return (pW - center_x), -(pH - center_y)

我执行屏幕转换的方式是添加x_offsety_offset 基本上移动中心。

现在,主循环中的真正的问题我将鼠标位置存储在数组pos = [0, 0] 中并每次更新

while 1:
    posX, posY = to_cartesian(*pygame.mouse.get_pos()) # mouse cords to caretsian
    if pygame.mouse.get_pressed(3)[0]:
        # Translate X
        translate = pos[0] - (pos[0] - posX)
        x_offset += translate
        # Translate Y
        translate = pos[1] - (pos[1] - posY)
        y_offset -= translate

    pos = [posX, posY]
    pygame.draw.rect(screen, color, (*to_pixels(0, 0), 20, 20)) # Drawing any shape to visualize

问题是,尽管转换很顺利,鼠标光标总是停留在屏幕的(0, 0) 坐标上。无论我点击哪里,它都会成为中心。

如果您对编写基本的pygame.init() 函数感到无聊,here 是一个工作示例,但它使用另一种形状来更好地说明问题,而不是 pygame.rect

【问题讨论】:

    标签: python math pygame


    【解决方案1】:

    问题是您的程序不记得旧的偏移值。

    Here is a modified version of your code 按预期工作。一种解决方案是使用标志mouse_held,当鼠标按下时变为True,释放时变为False。这可以用来保存旧的偏移值,这样下次按下鼠标时它们就不会被覆盖。

        # ...
    
        if pygame.mouse.get_pressed(3)[0]:
            mpos = pygame.mouse.get_pos()
    
            # mouse is just PRESSED down
            if not mouse_held:
                mouse_origin = mpos
                mouse_held = True
            
            # mouse is being HELD
            if mouse_held:
                offset_x = old_offset_x + mpos[0]-mouse_origin[0]
                offset_y = old_offset_y +mpos[1]-mouse_origin[1]
    
        # mouse is just RELEASED
        elif mouse_held:
            old_offset_x = offset_x
            old_offset_y = offset_y
            mouse_held = False
    
        # ...
    

    另外,您的 to_pixels 函数返回浮点数,这不是一件好事。

    【讨论】:

    • 很有意义,保存旧的偏移量是关键。但是在if mouse_held 中使用if 的原因是什么,因为它总是会评估为True
    • 鼠标刚按下时,mouse_held还是False是用来区分“刚按下”事件和“连续按住”的。因为当鼠标被点击时,我们需要保存发生的位置——并且还要检测按钮何时被释放(mouse_heldTrue 但鼠标不再被按下 --> 它只是被释放了)。我认为您也可以为此使用pygame.MOUSEBUTTONUP 事件。
    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    相关资源
    最近更新 更多