Sprite keeps shaking like crazy

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

How can i make my sprite follow my cursor withour shaking like crazy? Lowering the speed makes the shaking low too but it also makes my sprite in general slow, please i don’t know what to do right now

 const SPEED = 500 

func _ready():

func _process(delta):
    var vec = get_viewport().get_mouse_position() - self.position 
    vec = vec.normalized() * delta * SPEED 
    position += vec
:bust_in_silhouette: Reply From: psear

In each frame I think your character will overshoot the cursor, so it moves back in the direction of the cursor and overshoots again because each frame it’s moving by a few pixels.

Try this:

func _process(delta):
    var vec = get_viewport().get_mouse_position() - self.position 
    var movement = vec.normalized() * delta * SPEED 
    if movement.length_squared() < vec.length_squared():
        position += movement
        position += vec

This will only move your player if the movement vector you are adding to position is smaller than the distance to the mouse, otherwise it just moves to the mouse. You can use a ternary statement to achieve the same thing if you think the above is too many lines.

Also, I have used length_squared() instead of length() because this has better performance, and the actual numbers don’t matter because you’re just checking if one vector is bigger than the other.