Skip to content

Virtual mouse in Godot

A “virtual mouse” in this case is something like using a controller to emulate the mouse.

// Without taking ContentScaleFactor into account, the mouse coordinates you get could be wrong.
var mousePosition = GetViewport().GetMousePosition() * GetTree().Root.ContentScaleFactor;
if (@event.IsActionPressed("ui_page_down"))
{
Input.ParseInputEvent(
new InputEventMouseButton
{
Device = (int)InputEvent.DeviceIdEmulation,
Position = mousePosition,
ButtonIndex = MouseButton.Left,
Pressed = true,
}
);
}
// Do the same thing for ui_page_up but with Pressed = false

…when you press PgDn, it will send a mouse-down event. This on its own is not an entire click! You also need to press PgUp.

public override void _Process(double delta)
{
const int speed = 20;
Vector2 diff = Input.GetVector("cursor_left", "cursor_right", "cursor_up", "cursor_down") * speed;
if (!diff.IsZeroApprox())
{
Vector2 mousePos = GetViewport().GetMousePosition() * GetTree().Root.ContentScaleFactor;
InputEventMouseMotion eventMotion =
new()
{
Device = (int)InputEvent.DeviceIdEmulation,
Position = mousePos,
Relative = diff,
Velocity = diff * (float)delta,
};
// The event is still needed for the sake of MouseEntered/Exited signals
Input.ParseInputEvent(eventMotion);
// This only works on desktop platforms; see https://docs.godotengine.org/en/stable/classes/class_input.html#class-input-method-warp-mouse
Input.WarpMouse(mousePos + diff);
}
}