Search code examples
godot

How to make a 2D sprite follow mouse in Godot


Please provide minimal code example of Sprite following the mouse in Godot. There are complex and big sample projects, but I didn't found nothing small and clear.


Solution

  • Put the Sprite node in the scene, and attach the following script to it.

    const SPEED = 500
    
    func _process(delta):
        var vec = get_viewport().get_mouse_position() - self.position # getting the vector from self to the mouse
        vec = vec.normalized() * delta * SPEED # normalize it and multiply by time and speed
        position += vec # move by that vector