warp_mouse_position weird offset

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

Hello guys :slight_smile: :

I’m learning the warp_mouse_position(to: Vector2) method and I don’t know why, but I can’t make the mouse to warp in the desire position, this is my tree scene:

Node2d (parent) (script)

parent script:

extends Node2D

onready var Area2d_n := $Area2d
onready var Collisionshape2d_n:=$Collisionshape2d
onready var position_1:Vector2=  $Area2d.global_position

func _on_Defense_Area_mouse_exited() -> void:

these are the transforms position of the nodes:
Node2d= (0,0)
Area2d =(256,256)
Collisionshape2d= (0,0) relative to his parent Area2d

So my intention is to limit the mouse position. When the mouse leaves the Area2d go back to the center of the Area2d. But it adds a weird offset, and even trying this code:

 onready var position_1:Vector2=  $Area2d.get_global_transform_with_canvas().origin

Still give me a weird offset that is closest to 0,0 and not in the center of the Area2d center position. Anyone knows why and how to fix it?

Thanks a lot.

:bust_in_silhouette: Reply From: Maranpis

I answer myself :slight_smile:

I found the solution here:

I quote:

Screen space and world space aren’t equivalent. When you use
global_position you get coordinates in world space. Think about it:
the screen is limited by the bounds of the viewport, but the world
goes from -infinity to +infinity on all 3 (or 2 if 2d) axes. When you
take a node’s global position, you get a position that is somewhere on
this infinite plane. But the warp_mouse_position expects a coordinate
in within the bounds of the viewport.

You need to convert from world to screen space in order for that to
work. To do that, multiply by the viewport transform: new_mouse_pos =
get_viewport_transform() * global_position

Theoretically I think I can understand it but I would need concrete examples apart from the mouse to know where that conversion is needed.