【发布时间】: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_offset 和y_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。
【问题讨论】: