Move character to a certain point

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Adam
:warning: Old Version Published before Godot 3 was released.

I have the position of the mouse cursor, but how do I make the character move to that position?

:bust_in_silhouette: Reply From: ericdl

Find the vector from your character to the mouse position:

mousepoint = get_global_mouse_pos()
vector = (mousepoint - character.get_pos()).normalized()

And then move the character along the vector, although the function will be different depending if the character is a kinematic body or a rigidbody:

kinematic:

character.move(vector * SPEED * delta)

rigidbody:

character.set_linear_velocity(vector * SPEED * delta)

Sample project download: https://drive.google.com/file/d/0BwnfZQAEnciAeXBLeGRUTVd6Zjg/view?usp=sharing

You have to use global positions, not local :slight_smile: And maybe you will need to add some “close to mouse position, stop moving” logic to reduce shaking (moving thru cursor position and returning in next frame, miss exact position again, repeat) + on rigidbody, you should override integrate_forces func:

var _velocity = Vector2(0,0)
const SPEED = 100 # 100px per sec 
func _ready():
    set_process(true)
func _process(delta):
    var mouse_pos = get_global_mouse_pos()
    var my_pos = self.get_global_pos()
    var vector = mouse_pos - my_pos
    var length = vector.length()
    if length < 2: #2px, experiment with this value
        if length < 0.5:
            _velocity = Vector2(0,0) # full stop.
        else:
            _velocity = vector * SPEED * delta # sloooooowly
    else:
        _velocity = vector * SPEED * delta
func integrate_forces(state):
    state.set_linear_velocity(_velocity)

i dont test that code. Its comment, not answer :wink:


edit: messed up > and < :frowning:

splite | 2016-07-26 08:48

Thank you, it works. Your sample project was really helpful!

Adam | 2016-07-26 14:21