python - Pygame - 鼠标移动时变换屏幕
问题描述
我正在尝试实现转换,如果您按住鼠标左键并移动鼠标,屏幕将相应地转换。在谷歌地图中发生的同样的事情,按住和拖动屏幕的事情。我在 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()
函数,这里是一个工作示例,但不是pygame.rect
使用另一种形状来更好地说明问题
解决方案
问题是您的程序不记得旧的偏移值。
这是您的代码的修改版本,可以按预期工作。一种解决方案是您使用一个标志在鼠标按下和释放时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
函数返回浮点数,这不是一件好事。
推荐阅读
- python-3.x - concurrent futures behavior
- reactjs - Does react re render everything when we go to a new link?
- javascript - Wait for an Axios call to finish in Quasar / Vue
- outlook - How to use custom attributes in an e-mail template (outlook)?
- python - AttributeError:“Stud”对象在第 11 行没有属性“sno”
- wildfly - WildFly 9.2 的 CPU 利用率达到 100%
- oracle - 如何导出具有应用程序角色的 obiee12c 用户?
- flutter - if 语句中奇怪的 NULL 安全行为
- javascript - 是否可以在两个 wavesurfer 对象之间同步选定区域?
- python - 订阅者仅在 input() 命令后收到消息