Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
鼠标和输入坐标¶
关于¶
这个小教程旨在理清许多关于输入坐标、获取鼠标位置和屏幕分辨率等的常见错误。
硬件显示坐标¶
使用硬件坐标在编写要在 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_rect().size)
public override void _Input(InputEvent @event)
{
// Mouse in viewport coordinates.
if (@event is InputEventMouseButton eventMouseButton)
GD.Print("Mouse Click/Unclick at: ", eventMouseButton.Position);
else if (@event is InputEventMouseMotion eventMouseMotion)
GD.Print("Mouse Motion at: ", eventMouseMotion.Position);
// Print the size of the viewport.
GD.Print("Viewport Resolution is: ", GetViewportRect().Size);
}
另外,也可以从视口查询鼠标的坐标:
get_viewport().get_mouse_position()
GetViewport().GetMousePosition();
备注
鼠标模式为 Input.MOUSE_MODE_CAPTURED
时,InputEventMouseMotion
中的 event.position
值为屏幕中心。请使用 event.relative
代替 event.position
和 event.speed
来处理鼠标移动和位置变化。