NPC doesn't chase the character even though it should

Godot Version



The character Evil_Knight should chase the Warrior (the main character), but instead, it only runs in one direction (to the left) when the Warrior enters its detection area (CollisionShape2D). Here is the code for Evil_Knight:

extends CharacterBody2D

var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)

var chase = false
var speed = 400
@onready var anim = $AnimatedSprite2D

func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
var Warrior = $“…/…/Player/Warrior”
var direction = (Warrior.position - self.position).normalized()
if chase == true:
velocity.x = direction.x * speed“Run”)

	velocity.x = 0"Idle")
if direction.x < 0:
	$AnimatedSprite2D.flip_h = true
	$AnimatedSprite2D.flip_h = false

func _on_detector_body_entered(body):
if == “Warrior”:
chase = true

func _on_detector_body_exited(body):
if == “Warrior”:
chase = false

Could the issue be not with the code at all, and where should I look?

I’ve only recently started learning the engine, so I don’t understand many things yet.

Looks like it should work. Post more details or the entire project. It may be something else that’s not in this script.

Thank you for responding. There was a bug with the coordinates of the NPCs; I have fixed it already.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.