鼠标和输入坐标

关于

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

硬件显示坐标

Using hardware coordinates makes sense in the case of writing complex UIs meant to run on PC, such as editors, MMOs, tools, etc. However, it does not make as much sense outside of that scope.

视区显示坐标

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

GDScript

C#

  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_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: ", GetViewportRect().Size);
  10. }

Alternatively, it’s possible to ask the viewport for the mouse position:

GDScript

C#

  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.speed to process mouse movement and position changes.