Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

鼠标和输入坐标

关于

这个小教程旨在理清许多关于输入坐标、获取鼠标位置和屏幕分辨率等的常见错误。

硬件显示坐标

使用硬件坐标在编写要在 PC 上运行的复杂 UI 时是有意义的,比如编辑器、网络游戏、工具等。然而,在这个范围之外,它就没有那么大的意义了。

视口显示坐标

Godot 使用视口(Viewport)显示内容,并且视口可以通过若干选项进行缩放(参见 多分辨率 教程)。然后,使用节点中的函数来获得鼠标坐标和视口大小,例如:

func _input(event):
   # Mouse in viewport coordinates.
   if event is InputEventMouseButton:
       print("Mouse Click/Unclick at: ", event.position)
   elif event is InputEventMouseMotion:
       print("Mouse Motion at: ", event.position)

   # Print the size of the viewport.
   print("Viewport Resolution is: ", get_viewport().get_visible_rect().size)

另外,也可以从视口查询鼠标的坐标:

get_viewport().get_mouse_position()

备注

When the mouse mode is set to Input.MOUSE_MODE_CAPTURED, the event.position value from InputEventMouseMotion is the center of the screen. Use event.relative instead of event.position and event.velocity to process mouse movement and position changes.