How to make an AI stop before reaching the player?

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

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.

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

Wurzelpilz | 2021-07-25 15:10