Enemy Not Following The Player Correct

Godot Version



Hello im trying to make a survial game and now im making an enemy i’ve been trying to make the enemy follow and rotate depending on the player’s postion i made it kinda work but the enemy is facing sideways to the left instead to the front i tried changing the enemy/Mesh rotation it didnt work though. Enemy Script:

extends CharacterBody3D

var player = null

const SPEED = 0

@export var player_path : NodePath

@onready var nav_agent = $NavigationAgent3D
# Called when the node enters the scene tree for the first time.
func _ready():
    player = get_node(player_path)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    velocity = Vector3.ZERO
    var next_nav_point = nav_agent.get_next_path_position()
    velocity = (next_nav_point - global_transform.origin).normalized() * SPEED
    look_at(Vector3(player.global_position.x, global_position.y, player.global_position.z), Vector3.UP)

Good morning; ), I also go through this problem a lot, the error there, I believe it’s in the rotation of the z-axis, maybe put this negative number or mess with the rotation of the player’s MeshInstance3D. Anyway, I’ve saved here a script that does that:

extends CharacterBody3D

var life := 100

@onready var agent = $NavigationAgent3D

@export var player : CharacterBody3D
@export var speed : float = 4.5

@onready var player_sensor = $CollisionShape3D/RayCast3D

var player_on_area = false

func _physics_process(delta):

func _agent(delta):
	agent.target_position = player.global_position

	velocity = velocity.normalized()
	velocity = velocity.lerp((agent.get_next_path_position() - global_position) * speed, 5 * delta)

	if !there_is_any_ray_colliding():
		var target_look = (transform.origin + velocity.normalized())
		if !target_look.is_equal_approx(rotation):
			target_look.y = global_position.y
			look_at(target_look, Vector3.UP)

func there_is_any_ray_colliding() -> bool:
	if player_sensor != null:
		if player_sensor.is_colliding():
			return true
		for i in player_sensor.get_children():
			if i is RayCast3D and i.is_colliding():
				return true
	return false

I’ve optimized the code to be just about walking and spinning, but I think that’s okay. Oh! don’t forget to determine the Player node in the parameters exported from the script!