0 votes

I need Touch location (specifically, x and z) in 3D scene. In 2D I used to get it by event.position, what's the 3D equivalent?

Thanks for your time!

Godot version 3.2.3
in Engine by (305 points)

2 Answers

0 votes
Best answer
func touch_location(position, mask = 1) -> Vector3:
    var camera = get_viewport().get_camera()
    var ray_length = 1000
    var ray_start = camera.project_ray_origin(position)
    var ray_end = ray_start + camera.project_ray_normal(position) * ray_length
    var space_state = camera.get_world().direct_space_state
    var result = space_State.intersect_ray(ray_start, ray_end, [], mask)
    if not result:
        return Vector3()
    return result.position

func _input(event):
    if event is InputEventMouseButton:
        if event.pressed:
            var position = touch_location(event.position)
by (3,282 points)
selected by

Huge thanks once again!

How am I supposed to set $my3Dobject position to touch_location(event.position) based on your script?

I need x and z (y is set to zero).

In 2D I used to write $my2Dobject.position.x = event.position.x and likewise for y. I have no idea how to accomplish it in 3D.

$my3Dobject.global_transform.origin = touch_location(event.position)

equates to

#Left and Right

$my3Dobject.global_transform.origin.x = touch_location(event.position).x

#Up and Down

$my3Dobject.global_transform.origin.y = touch_location(event.position).y

#Forward and Backwards

$my3Dobject.global_transform.origin.z = touch_location(event.position).z

You are perfect, Wakatta!

0 votes

I hope thats what your searching for
https://www.youtube.com/watch?v=xPHn4miUxuc&t=45s

by (254 points)

Thank you for the reply! The link you sent is very useful indeed for my other needs. Though what I want to accomplish here is to move a 3D object to the location of Touch. I set the y axis to 0 so that it's always level to the scene. And I want to equal the x and z of an object to the x and z of Touch.

In 2D I used to write var px = event.position.x and var py = event.position.y and then under process I would write object.position.x = px and object.position.y = py

Or I would directly write under input object.position.x = event.position.x and likewise for y.

In 3D I have no idea how to accomplish it.

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.