How do I make NPCs wait few seconds to navigate again?

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

My NPCs should navigate to a predefined position and once they reached it, they should wait for few seconds to navigate to another location. However when I run the game at its current state, they go to the very first destination and never move after that. I think my idle_state function is overwriting whenever timeout signal changes state. Here is the code:

> extends "res://Characters/NPCs/PlayerDetection.gd"

onready var destinations = $"../../Destinations".get_children()
onready var timer = $Timer

onready var navAgent : NavigationAgent2D
var target_pos: Vector2

var state = NAVIGATE

enum {
	IDLE,
	NAVIGATE
}

func _ready():
	navAgent = $NavigationAgent2D
	randomize()
	decide_dest()

func _physics_process(delta):
	match state:
		NAVIGATE:
			navigate()
		IDLE:
			idle_state()

func decide_dest():
	target_pos = destinations[randi() % destinations.size() - 1].position

func navigate():
	navAgent.set_target_location(target_pos)
	var target_loc = navAgent.get_next_location()
	look_at(target_loc)
	var direction = position.direction_to(target_loc)
	var velocity = navAgent.max_speed * direction
	move_and_slide(velocity)
	if navAgent.is_target_reached():
		state = "IDLE"

func idle_state():
	if timer.is_stopped():
		timer.start()
	
func _on_Timer_timeout():
	decide_dest()
	state = NAVIGATE
:bust_in_silhouette: Reply From: rossunger

make sure your timer is set to one-shot.

How have you debugged the issue? did you try placing break-points at state= “IDLE” to make sure that works? have you tried print(target_pos) to make sure that that is being set correctly?

:bust_in_silhouette: Reply From: sporx13

Problem might be that you change state in 2 different ways"

in navigate():
state = “IDLE”

in _on_Timer_timeout():
state = NAVIGATE (without quotes)

So you probably in reality never change to IDLE state (?)