0 votes

How can I get the point clicked on the terrain, to move my player to that position? Im using the terrain plugin, but I would like to know how to do it in case Im using a plane or other mesh.

asked Dec 14, 2019 in Engine by rogerdv (139 points)

I've tried doing stuff like this (with mixed results). IIRC, when the player clicks on the screen, a ray can be cast from where they clicked (more information on that can be found here). Where that ray intersects the geometry (in one game, I used the code get_world().direct_space_state.intersect_ray() to figure out what geometry intersected the ray).

Hope that helps.

oh that's actually useful.

Forgot to mention that intersect_ray() also takes parameters.

1 Answer

0 votes
Best answer

I have tried this previously , just put this script on a camera and read the position of the clickpos variable and it should work ... and make sure whatever mesh you are using it should have a static body child or parent , and a collision mesh , because you need colliders to make it work

extends Camera
var ray=RayCast.new()
var clickpos= Vector3(0,0,0)
func _ready():
    add_child(ray)
    ray.enabled=true

func _input(event):
    var clicked = (GetMouseClick(event))

func GetMouseClick(event):
    var distance_from_camera = far 
    if event is InputEventMouseButton:
            var from = project_ray_origin(event.position);
            var to = from + project_ray_normal(event.position) * distance_from_camera;
            ray.cast_to = to-global_transform.origin
            if (event is InputEventMouseButton):
                if (event.pressed == false and event.button_index == 1): #check if Left Click is released 
                    if ray.is_colliding():
                        var raypoint = ray.get_collision_point()
                        return (raypoint)
answered Dec 14, 2019 by Xtremezero (288 points)
selected Dec 16, 2019 by rogerdv

A little question (Im still a newbie with Godot), how do I read clickpos from another script? Or can I do the movement from inside that script attached to the camera?

in your other object script write this :

get_node("camera_path").click_pos

remember to replace camera_path with the suitable path for the camera in your project

BTW, I dont see clickpos being assigned in any place. Shouldnt be this way?

func _input(event):
clickpos = (GetMouseClick(event))

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.