get_viewport().size.x doesn't match real max value of get_viewport().get_mouse_position().x

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By VastView

My code:

func _input(event):
	if event is InputEventMouseMotion:
		print("viewport.size.x: %s" % get_viewport().size.x)
		print("viewport.mouse.x: %s" % get_viewport().get_mouse_position().x)

If I play a scene with the mentioned code running, and I move my mouse as far as I can to the right of the game window, this is the console output I get:

viewport.size.x: 2560
viewport.mouse.x: 1919.249878

As you can see, the mouse position doesn’t approximate the viewport’s apparent size when it’s all the way to the right edge of the screen. This is a problem for me, since I want to know how close the mouse is to the right edge of the game screen.

I’m assuming this might have something to do with the font/app scaling in Windows and how Godot calculates viewport mouse position. Also, using get_global_mouse_position().x has the same problem and gives the same outputs when the ingame camera is placed with it’s top left corner at the world origin.

I just ran this on a test project and I couldn’t duplicate, the mouse position and viewport size married perfectly. OS.get_window_size() got me the same result too.

Try to isolate the issue, make a fresh test project and see if you get the same issue. Sorry I can’t be more help, very strange issue.

DaddyMonster | 2022-01-10 10:58

Try how does it works fullscreen and windowed.
Experiment with get_viewport().get_visible_rect()

Inces | 2022-01-10 16:47

Hi, I figured out where things goes wrong when I tried recreating the issue.

It seems that setting the Stretch Mode to 2D in Project Settings display/window/stretch/mode causes the problem.

You need to set a different test width and height for your window in project settings than your default window size, or resize the game window manually, then the problem will appear.

VastView | 2022-01-10 19:15

I still don’t know why the problem exists and how to fix it.

For now I did a workaround by having an invisible Control node positioned at the bottom right of the screen, and reading it’s position to get the current screen width.

VastView | 2022-01-17 00:42