I have an enemy that uses a navigation agent to traverse but upon reaching its target position (in this case, the player) it begins to jitter. It is very distracting and I am curious as how I may remedy this. I have the suspicion it occurs due to the navigation agent being imprecise and attempting to move when its already reach the target position.
Enemy Code
extends CharacterBody2D
var health = 3
var move_speed = 150
var held = false
var dead = false
@onready var player = global_player
@onready var lair = global_position
var direction = null
func _ready():
add_to_group("pick_up")
call_deferred("actor_setup")
func _physics_process(_delta):
if health <= 0:
dead = true
if !$NavigationAgent2D.is_target_reached() and !dead:
var new_point_dir = to_local($NavigationAgent2D.get_next_path_position()).normalized()
velocity = new_point_dir * move_speed
move_and_slide()
elif dead:
$AnimatedSprite2D.play("dead")
velocity = Vector2(0, 0)
if held:
position = global_player.item_pos
#$AnimationPlayer.stop()
if Input.is_action_just_pressed("action"):
global_player.item_held = false
held = false
else:
global_position = global_position
#$AnimationPlayer.play("idle_flash")
func actor_setup():
await get_tree().physics_frame
$NavigationAgent2D.target_position = lair
func _on_timer_timeout():
if $NavigationAgent2D.target_position != round(player.player_pos):
$NavigationAgent2D.target_position = round(player.player_pos)
$Timer.start()
So this recorded in a weird frame rate but the dragon wildly twists and shakes when unable to reach the players position or when it has reached the player position
What did you set in the target_desired_distance property of your NavigationAgent2D?
It seems like you need to increase this value, otherwise your dragon overshoots the target every time, has to turn back and overshoots again, rinse and repeat - hence the jitter.
See the documentation that explains how to fix it, try it out:
Hey, I had the same problem, and didn’t find the solution of setting target_desired_distance to a higher value working - the jittering persisted. So I did this: