Up to date

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

Mouse and input coordinates

About

The reason for this small tutorial is to clear up many common mistakes about input coordinates, obtaining mouse position and screen resolution, etc.

Hardware display coordinates

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.

Viewport display coordinates

Godot uses viewports to display content, and viewports can be scaled by several options (see Multiple resolutions tutorial). Use, then, the functions in nodes to obtain the mouse coordinates and viewport size, for example:

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_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:

GDScriptC#

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

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