How to make the player object follow the movements of the mouse/touch (not position)

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

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

:bust_in_silhouette: Reply From: magicalogic

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.

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

jtruji68 | 2023-01-06 09:10