0 votes

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.

in Engine by (95 points)

2 Answers

0 votes

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.

by (271 points)

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.

+1 vote

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;
by (95 points)
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 Frequently asked questions and 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 [email protected] with your username.