鼠标和输入坐标

关于

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

硬件显示坐标

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

视口显示坐标

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

GDScriptC#

  1. func _input(event):
  2. # Mouse in viewport coordinates.
  3. if event is InputEventMouseButton:
  4. print("Mouse Click/Unclick at: ", event.position)
  5. elif event is InputEventMouseMotion:
  6. print("Mouse Motion at: ", event.position)
  7. # Print the size of the viewport.
  8. print("Viewport Resolution is: ", get_viewport().get_visible_rect().size)
  1. public override void _Input(InputEvent @event)
  2. {
  3. // Mouse in viewport coordinates.
  4. if (@event is InputEventMouseButton eventMouseButton)
  5. GD.Print("Mouse Click/Unclick at: ", eventMouseButton.Position);
  6. else if (@event is InputEventMouseMotion eventMouseMotion)
  7. GD.Print("Mouse Motion at: ", eventMouseMotion.Position);
  8. // Print the size of the viewport.
  9. GD.Print("Viewport Resolution is: ", GetViewport().GetVisibleRect().Size);
  10. }

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

GDScriptC#

  1. get_viewport().get_mouse_position()
  1. GetViewport().GetMousePosition();

备注

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.