Search code examples
godotgdscript

Navigation2d use with move_and_slide in Godot


Rewritten and Edited for clarity. Assume that I have a 2d platformer like the following example:

https://github.com/godotengine/godot-demo-projects/blob/master/2d/kinematic_character/player.gd

Now... Say I have the player location (vector2) and the enemy location (vector2). The enemy movement works just like the player in the above example. I use get_simple_path to build an array of pre-existing points that lead from the enemy location to the player location. How do I use that array with move_and_slide to get the enemy from point A to point B?


Solution

  • You could try the following:

    const GRAVITY = 1000
    const SLOPE_SLIDE_STOP = false
    
    var speed = 250
    var velocity = Vector2()
    
    var points = [Vector2(100, 200), Vector2(200, 400), Vector2(400, 800)]
    var current_point = null
    
    func _physics_process(delta):
        if points and current_point is null:
            current_point = points.pop_front()
    
        if current_point:
            if current_point.distance_to(position) > 0:
                target_direction = (position - current_point).normalized()
    
                velocity.y += delta * GRAVITY
    
                velocity = lerp(velocity, target_speed, 0.1)
                velocity = move_and_slide(velocity, target_direction, SLOPE_SLIDE_STOP)
            else:
                current_point = null