How to make AI chase the player?

Godot Version



I tried to make my enemy follow my player however, it’s not moving toward my player. It’s still standing there in the same spot.

extends CharacterBody3D

var speed = 5
var accel = 10

@onready var nav: NavigationAgent3D = $NavigationAgent3D

func _physics_process(delta):
	var direction = Vector3() = direction = direction.normalized()
	velocity = velocity.lerp(direction * speed , accel * delta)

You have to call get_next_path_position() on the nav agent in physic_process:

Note: After setting the target_position property, the get_next_path_position method must be used once every physics frame to update the internal path logic of the navigation agent. The vector position it returns should be used as the next movement position for the agent’s parent node.

Uh sorry, I kinda new at coding the Gscript.

Can you explain little more? Where I put “get_next_path_position()” in Gscript?

Under func _physics_process(delta): and below = direction = direction.normalized()?

Setting the target_position can be done anywhere.
You can do it in physics_process, but from what I’ve heard this is not always ideal as this apparently triggers the recalculation of the path and with lots of agents this can be demanding. But unless this doesn’t cause any performance problems you can put it in physics. I believe it doesn’t matter at which point, but I’d say before getting the next path position for euh let’s call it “keeping the order correct you usually think it should work” (set target position, get next path pos, then move there).


func _physics_process(delta: float) -> void:	
    agent.target_position = player.global_position
    var next_position = agent.get_next_path_position()
    var direction = global_position.direction_to(next_position)
	if not is_on_floor():
		velocity.y -= gravity * delta

	if direction:
		velocity.x = direction.x * speed
		velocity.z = direction.z * speed
		velocity.x = move_toward(velocity.x, 0, speed)
		velocity.z = move_toward(velocity.z, 0, speed)

Did you bake a navmesh? In your video I couldn’t see it.

Yes, I did and it doesn’t show up as baking no matter how I click.

That’s strange. Right now I can’t see why.