How do you implement a Navigation2D to AI?

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

So i watch GDSripts Navigation tutorial and understand how the Nav2D and its Nav Mesh work. I want to know ,do I let the Nav2D control my enemy’s AI movement in its script or do i make it as a script for my enemy script to call its move methods. At the moment I just took the script from the tutorial and connected a target to my mouse to act as the player to see if i can make it follow and it works but i dont really know how to add it to my enemy AI script.

:bust_in_silhouette: Reply From: Magso

The get_simple_path() method for the navigation node uses the navigation mesh to create a path for KinematicBodies to follow using move_and_slide(), how to use move_and_slide depends on what behaviour you’re wanting such as if a character is running and turning, you would use move_and_slide(global_transform.basis.xform(Vector3.FORWARD)) and look_at().

So sould it be a child or parent of the enemy scene or a separate scene itself cause in trying to figure out how to have its nav mesh out all the time for multiple enemies.

Newby | 2020-02-02 00:14

The navigation and navmesh nodes should be parents of the map to bake the navmesh, after that they just need to exist in the scene and the enemy needs to have the path from navigation.get_simple_path().

Magso | 2020-02-02 00:42

Ok so if my scene has a Nav2D all i need to do is have a line of code like this in my enemy scene?

$Nav2D.get_simple_path

So will it work like a position Vector2 for move_and_slide?

Newby | 2020-02-02 03:46

It’s not quite that straight forward. get_simple_path returns an array of Vector3s that the AI can follow, so the code needs to go through the array of Vector3 points to direct the AI through, here’s an example.

var nav_path
var path_index : int

func _ready():
    while true:
        yield(get_tree().create_timer(0.2),"timeout")
        nav_path = navigation.get_simple_path(from, to, optimize true/false)
        path_index = 0

func _process(delta):
    move_and_slide(global_transform.basis.xform(Vector3.FORWARD))
    look_at(nav_path[path_index])
    if global_transform.origin.distance_to(nav_path[path_index].global_transform.origin) < 0.1:
        path_index += 1

Magso | 2020-02-02 14:41