#How to capture the actual mouse position [Godot 4.3 C#]

1 messages · Page 1 of 1 (latest)

glacial sail
#

Hi, I recently found a bug in my game where I'm trying to move the mouse cursor with keyboard arrows. I'm using GetViewport().GetMousePosition() on the root element of the scene to get the mouse position, add a vector of shift and update it with Input.WarpMouse function.

Input.WarpMouse(GetViewport().GetMousePosition() + mouse_vel);

This works fine in windowed mode when the window is not resized.

The moment I resize the window, the function returns bogus data and actually diverges to single point in the screen.

The issue is reproducible when you select in Project settings Display->Windw->Stretch Mode to "viewport" and Aspect to "keep". If I change those to disabled, the issue no longer happens, so it must be related to the stretching code and the black bars that appear with it.

Has anyone seen this? Have you found a workaround?

glacial sail
#

Answering my own question:
Input.WarpMouse() operates in the Window coordinates, whereas GetViewport()GetMousePosition() operates in the Viewport scope that could be scaled down or up to keep aspect ratio. (and returns unscaled values, so if viewport was set to 1920x1080 it will return values from that range)

So modified the code as follows:

var offset = GetViewport().GetScreenTransform().Origin;  // black bars at top/bottom or sides
var scale = GetViewport().GetScreenTransform().Scale;  // current scale factor of the window to viewport transform
var position = GetViewport().GetMousePosition();  // position of mouse in the viewport
var newPosition = position * scale + offset + mouse_vel;
Input.WarpMouse(newPosition);

so we first scale the Viewport position to be expressed in the Window coordinates, and then offset by black bars and mouse_vel is my directional velocity for moving the mouse with arrows on keyboard or controllers dpad / joystick.