0 votes

Hi, i was writing a script to move my player with my mouse/touch input but the problem is the character moves to the mouse position instead of following/copying his movements.

How can i make that the character moves by touch movement and not by its position?
so, if i drag the mouse/touch input slightly to the right the character should move slightly to the right instead of going where the mouse is located, like in this gif.
enter image description here

my current code is:

func _input(event):
if event is InputEventScreenDrag:
    position.x = lerp(position.x, get_global_mouse_position().x, speed)
    position.y = lerp(position.y, get_global_mouse_position().y, speed)

thanks in advance

Godot version v3.5.1
in Engine by (19 points)
edited by

1 Answer

+1 vote
Best answer

You need to get the offset of the object from the mouse position when the left mouse button is just clicked.

var offset := Vector2.ZERO
func _process(delta):
    if Input.is_action_just_pressed("Click"):
        offset = get_global_mouse_position - global_position

Then in your _input function above add a variable to hold the desired new position.
var new_position = get_global_mouse_position - offset
Now instead of lerping from position to global mouse position, lerp from global_position to new_position.

It's important to use global position rather than just position to avoid issues when the node is rotated.
Also add the "Click" action in your project settings.

by (2,017 points)
selected by

Thanks, I found a workaround but your solution is far more elegant. For the ones reading this, remember when to select "All devices" when adding the Input "Click" on the project Settings

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.