+3 votes

Hello! I was trying to get the global position based on where the finger has touched on a mobile touchscreen, somewhat similar to the function: get_global_mouse_position() where the mouse global position is captured. I thought this was done by using this code:

func _input(event):

    if event is InputEventScreenDrag:
        touch_position = event.position

The touch_position represents the Vector2() coordinates based on the event.position. Unfortunately though this only captures the position the finger is touching on the screen. Say that my resolution screen size is set at 400x224 pixels then I can only get the position in that range such as 345x120 or 20x200 pixel position. is there a better way to get the global position capture based on the position of the touchscreen resolution limit?

in Engine by (200 points)

Unfortunately though this only captures the position the finger is touching on the screen.

I'm not certain 100% what you're asking for.

  1. Do you want a more precise location of the finger touch?
  2. Is the location you get not accurate enough?
  3. Do you want to require that the user make more accurate finger placement?

1 Answer

+9 votes

For anyone wondering, you have to use transformation matrix to get world coordinates from touch position.

world_position = get_canvas_transform().xform_inv(event.position)

It took me quit a while to figure it out. So i hope it will help you save some time.
Basically this solution is is the same as get_global_mouse_position(). But that function cannot be used when you are working with multitouch inputs.

by (34 points)

Is this supposed to work when using a camera2D? I'm getting completely different coordinates with to with get_canvas_transform().xform_inv(event.position) than I am with get_global_mouse_position()

For anyone who has this problem, this works in the cases where event.position is returning a vector relative to the viewport and you need the global position of it:

target = get_canvas_transform().affine_inverse().xform(event.position)

I found it here: https://github.com/godotengine/godot/blob/master/scene/main/canvas_item.cpp

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.