How to map node position to screen pixel position for mouse warp?

Godot Version

v4.6.stable.official [89cea1439]

Question

I’m trying to warp mouse to the position of a node. It works fine when running the project.

When I change the window size, warp starts having an offset. And the offset changes depending on the window size. This issue happens when the display/window/stretch/mode is set as canvas_items. When it’s set as disabled, it works fine.

Any ideas how to solve this?

There’s actually four different warp_mouse functions, on Control, DisplayServer, Input, and Viewport. I’ll assume you’re using one of the latter three, as they all work similarly. Those functions warp to the mouse to a position relative to an origin at the upper left corner of the currently focused Window Manager game window (from the docs). Therefore you need to convert the node’s position to the window’s coordinates.

This page explains in depth how to do it, but the simple version is to use CanvasItem.get_global_transform_with_canvas() (assuming that the node you want to warp it to is a CanvasItem).

Thank you @paintsimmon. I thought Input.warp_mouse() was the only way. It’s really helpful to know there are other ways to warp the mouse position.

I think I should use Viewport.warp_mouse() because CanvasItem.get_global_transform_with_canvas()gives a viewport coordinate.

So I tried this, there is still offset **. It’s still better as the offset seems to be same, independent from the screen size. So I must be missing something.

I created a simple scene to test it. Here is my Display setting, scene and the code under Main node. Maybe you can figure out what’s wrong.

extends Node2D

@export var polygon_2d: Polygon2D


func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		var mouse_pos = polygon_2d.get_global_transform_with_canvas()*polygon_2d.position
		polygon_2d.get_viewport().warp_mouse(mouse_pos)

**Note: I realized that it’s warping to the 2 * position of the polygon2D for some reason.. So if the polygon pos is Vector2(80,90), it warps mouse to Vector2(160,180)