Enemy scene is not moving toward player scene, when the player enters a collisionshape2d zone

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Linkio

So I have been following HeartBeast’s action rpg tutorial, trying to learn the engine, and I’ve been following along with him. I got to the section where we started making the Enemy AI.

The enemy scene instances as scene called PlayerDetectionZone which has a CollisionShape2d as a child of it. When the player enters the zone defined by the CollisionShape2d the bat should start moving toward the player, but it does not.

Here is some of the code for my enemy

var velocity = Vector2.ZERO
var knockback = Vector2.ZERO

var state = IDLE

onready var stats = $Stats
onready var playerDetectionZone = $PlayerDetectionZone

func  _physics_process(delta):
	knockback = knockback.move_toward(Vector2.ZERO, FRICTION * delta)
	knockback = move_and_slide(knockback)
	
	match state:
		IDLE:
			velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)
			seek_player()
			
		WANDER:
			pass
		
		CHASE:
			var player = playerDetectionZone.player
			if player != null:
				var direction = (player.global_position - global_position).normalized()
				velocity.move_toward(direction * MAX_SPEED, ACCELERATION * delta)
	
	velocity = move_and_slide(velocity)
	
			
func seek_player():
	if playerDetectionZone.can_see_player():
		state = CHASE

Here is my code for the player detection zone:

extends Area2D

var player = null

func can_see_player():
	return player != null

func _on_PlayerDetectionZone_body_entered(body):
	player = body

func _on_PlayerDetectionZone_body_exited(body):
	player = null

I’ve been putting print statements through out the code too try and isolate which parts are failing, but everything seems to be called correctly. Signals are fired when the player enters, the chase state is called. I have no idea what is causing the problem. The enemy simply does not move. If you need any more information I can provide it.

Thanks.

:bust_in_silhouette: Reply From: jgodfrey

In that CHASE state, I think you want this:

velocity = velocity.move_toward(direction * MAX_SPEED, ACCELERATION * delta)

Notice, that I’ve added the velocity = part at the beginning…