mouse_and_input_coordinates.rst 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. .. _doc_mouse_and_input_coordinates:
  2. Mouse and input coordinates
  3. ===========================
  4. About
  5. -----
  6. The reason for this small tutorial is to clear up many common mistakes
  7. about input coordinates, obtaining mouse position and screen resolution,
  8. etc.
  9. Hardware display coordinates
  10. ----------------------------
  11. Using hardware coordinates makes sense in the case of writing complex
  12. UIs meant to run on PC, such as editors, MMOs, tools, etc. However, it does
  13. not make as much sense outside of that scope.
  14. Viewport display coordinates
  15. ----------------------------
  16. Godot uses viewports to display content, and viewports can be scaled by
  17. several options (see :ref:`doc_multiple_resolutions` tutorial). Use, then, the
  18. functions in nodes to obtain the mouse coordinates and viewport size,
  19. for example:
  20. .. tabs::
  21. .. code-tab:: gdscript GDScript
  22. func _input(event):
  23. # Mouse in viewport coordinates.
  24. if event is InputEventMouseButton:
  25. print("Mouse Click/Unclick at: ", event.position)
  26. elif event is InputEventMouseMotion:
  27. print("Mouse Motion at: ", event.position)
  28. # Print the size of the viewport.
  29. print("Viewport Resolution is: ", get_viewport().get_visible_rect().size)
  30. .. code-tab:: csharp
  31. public override void _Input(InputEvent @event)
  32. {
  33. // Mouse in viewport coordinates.
  34. if (@event is InputEventMouseButton eventMouseButton)
  35. GD.Print("Mouse Click/Unclick at: ", eventMouseButton.Position);
  36. else if (@event is InputEventMouseMotion eventMouseMotion)
  37. GD.Print("Mouse Motion at: ", eventMouseMotion.Position);
  38. // Print the size of the viewport.
  39. GD.Print("Viewport Resolution is: ", GetViewport().GetVisibleRect().Size);
  40. }
  41. Alternatively, it's possible to ask the viewport for the mouse position:
  42. .. tabs::
  43. .. code-tab:: gdscript GDScript
  44. get_viewport().get_mouse_position()
  45. .. code-tab:: csharp
  46. GetViewport().GetMousePosition();
  47. .. note:: 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.