Godot Version
4.2.1
Question
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
anim.play(“Run”)
else:
velocity.x = 0
anim.play("Idle")
if direction.x < 0:
$AnimatedSprite2D.flip_h = true
else:
$AnimatedSprite2D.flip_h = false
move_and_slide()
func _on_detector_body_entered(body):
if body.name == “Warrior”:
chase = true
func _on_detector_body_exited(body):
if body.name == “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.