0 votes

I have an AI which follows the player using Navmesh, but it goes into the player. I want it to stop near the player so it won't go into it. So far, this is my code:

extends KinematicBody

var path = []
var path_node = 0

var speed = 7

onready var nav = get_parent()
onready var player = $"../../player"

func _ready():
    pass

func _physics_process(_delta):
    if path_node < path.size():
        var direction = (path[path_node] - global_transform.origin)
        if direction.length() < 1:
            path_node += 1
        else:
            move_and_slide(direction.normalized() * speed, Vector3.UP)

func move_to(target_pos):
    path = nav.get_simple_path(global_transform.origin, target_pos)
    path_node = 0

func _on_Timer_timeout():
    move_to(player.global_transform.origin)

This is being made in 3D.

Godot version v3.3.2
in Engine by (55 points)

did you tried

   if position.distance_to(player.position) > 1: 
            move_and_slide(direction.normalized() * speed, Vector3.UP)

or maybe do it here:

if path_node < path.size() and  position.distance_to(player.position) > 1: 
   your code

generally "position.distance_to" is a good candidate for this

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.