I have a sub-viewport with a 2D scene instanced as a child. On this scene I draw a grid and I want to be able to click inside of the grid and place a sprite on the tile that I clicked on.
To achieve this I use following code:
var mouse_pos = a_preview_scene.get_global_mouse_position()
var point = _pos_to_grid_point(mouse_pos)
if a_point_vec != point || a_point == null:
This works fine as long as the window size doesn't change. I have stretch_mode 2D and aspect keep in the project settings, and if I resize the window to be wider or higher
CanvasItem.get_global_mouse_position() starts to give me wrong values. (Note: In this case the size of the root viewport is still the default value, only black bars appear).
This offset caused by the black bars can be easily fixed by doing:
var root = get_tree().get_root()
var bars = (OS.window_size - root.size) / 2
mouse_pos -= bars
I believe you also have to take the viewport stretch into account if
Viewport.size_override_stretch is active.
(By calculating the factor
sub_viewport.size_override / sub_viewport.size)
But if I now happen to resize the root viewports size, either by making the window size smaller or by switching to full screen (The sub-viewport size stays the same), everything breaks apart and I'm left with a coordinate I have no idea how to make use of. And even if that worked, changing properties of the current camera 2D would break it too.
So I'm asking, how do I always get the correct global mouse coordinates inside a sub-viewport?
Minimal Reproduction Project: https://drive.google.com/drive/folders/1nE083OXXZd5RiV99HIwMIUe5D0zDrJx3?usp=sharing