(3D) Make object follow mouse

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

I’m trying to get a sword to follow the mouse position, while also having player movement (so you’d move with WASD and mouse is the sword).

I’ve searched for solutions but they cause problems when you have a moving character and camera, can anyone please help? Thank you for reading.

:bust_in_silhouette: Reply From: Xian

Use the mouse positon (or as godot calls it translation) read this
InputEventMouse has global_position and position properties, both returning a vector2. Use this data as a target for the next position your sword has to follow. Using func _process(delta): so that it’ll constantly move towards the mouse.

This doesn’t seem to work when you have a camera that rotates around an enemy using look_at() which is what I’m doing, the sword just goes somewhere completely different.

Zero | 2020-09-01 07:27

:bust_in_silhouette: Reply From: Zero

I ended up finding a solution from this link that worked for me:

func _input(event):
if (event is InputEventMouseButton):
    if (event.pressed == true and event.button_index == 1):
        var camera = get_node("Camera")
        var from = camera.project_ray_origin(event.position);
        var to = from + camera_project_ray_normal(event.position) * distance_from_camera;
        # Apply the position to whatever object you want (we'll assume a node named "Cube")
        get_node("Cube").global_transform.origin = to;