Enemy ai not working

Godot Version

4.2.1

Question

My enemy is not moving in my top down game I don't know why I just started a tutorial on how to do it and I don't know if this is something that I am missing please help

extends CharacterBody2D

@export var speed: float = 120.0
var player: Node2D
var chasing := false

func _physics_process(delta):
	print("CHASE =", chasing, "VEL =", velocity) # debug print

	if chasing and player:
		var dir = (player.position - position)
		print("DIR =", dir)
		
		if dir.length() > 2:
			velocity = dir.normalized() * speed
		else:
			velocity = Vector2.ZERO
	else:
		velocity = Vector2.ZERO

	move_and_slide()

func _on_detection_area_body_entered(body):
	print("ENTER:", body)
	chasing = true
	player = body

func _on_detection_area_body_exited(body):
	print("EXIT:", body)
	if body == player:
		chasing = false
		player = null

Your character may be detecting it’s own body, which is zero units away so it’s velocity is always zero. What do your print statements say?

You should add a condition to your body entered function, I like using is to detect type and a class_name Player on my player script.

func _on_detection_area_body_entered(body):
	if body is Player:
		print("ENTER:", body)
		chasing = true
		player = body

I use the web editor so I don’t have prints.

1 Like

You should be able to see prints in your web console, usually F12 will open this but you may have to click around to prevent Godot from stealing this input.

okay, I am testing both of those things now. One of them is ought to work

it says that player is a variable but does not have a type

I’m guessing you mean on this line of the sample?

You would have to add a class_name Player on your player script for this to function as you’d like. If you don’t want a class_name then you could check against the body’s name

how do you use a class_name?

You would write it at the top of your player script, this registers the script as a type

extends CharacterBody2D
class_name Player

here is a video of the bug

The enemy is suppose to start chasing me when I am in the big circle.

It seems like you’ve put the condition on the body exited function, not the body entered.

The slime attaching to the player’s head is likely because the CharacterBody2D believes the player is a moving platform, since this is a top-down game you should set all of your CharacterBody2Ds to motion mode “Floating” which does not take “moving platforms” below them into account, and every collision shape is treated as a wall instead of a floor/wall/ceiling.

those both don’t work. Should I just fully rebuild the emeny ai form a different turtauil of keep debuging this?