Enemy Walking script not working

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

I have created a player detection script so that my enemy walks toward the player, but it only walks down and nowhere else.

extends KinematicBody2D

var speed = 50
var velocity = Vector2()
var player = preload("res://Player.tscn").instance()
var BackEntered = null
var RightEntered = null
var LeftEntered = null
var ForwardEntered = null

func _physics_process(delta):
    velocity = Vector2()
    if BackEntered:
	velocity.y -= speed
	$Skeleton.play("SWalkB")
elif BackEntered == null:
	velocity.y = 0
	
if RightEntered:
	velocity.x = speed
	$Skeleton.play("SWalkR")
elif RightEntered == null:
	velocity.x = 0
	
if LeftEntered: 
	velocity.x -= speed
	$Skeleton.play("SWalkL")
elif LeftEntered == null:
	velocity.x = 0

if ForwardEntered:
	velocity.y = speed
	$Skeleton.play("SWalkF")
elif ForwardEntered == null:
	velocity.y = 0
	
else:
	velocity.y = 0
	velocity.x = 0
	
func _process(delta):
    velocity = move_and_slide(velocity)

#area entered
func _on_DetectPlayerBack_body_entered(body):
BackEntered = player
func _on_DetectPlayerRight_body_entered(body):
RightEntered = player
func _on_DetectPlayerLeft_body_entered(body):
LeftEntered = player
func _on_DetectPlayerForward_body_entered(body):
ForwardEntered = player

#area exited
func _on_DetectPlayerBack_body_exited(body):
BackEntered = null
func _on_DetectPlayerRight_body_exited(body):
RightEntered = null
func _on_DetectPlayerLeft_body_exited(body):
LeftEntered = null
func _on_DetectPlayerForward_body_exited(body):
ForwardEntered = null

When the direction is negative, you do velocity.y -= speed, but when the direction is positive, you do velocity.y = speed. -= is just short hand for velocity.y = velocity.y - speed, meaning you keep substracting speed every frame, which makes your enemy accelerate. But velocity.y = speed is only setting the velocity to 50, meaning if it were moving, it would do so a lot slower than the other direction. My guess is that the enemy is moving, but you don’t notice since the velocity is so low in the up or right directions. If I’m correct, then you also haven’t tested the left direction, since you use -= there as well.

I guess that for forward and right, you meant to write velocity.y += speed and velocity.x += speed respectively.

Bernard Cloutier | 2020-10-09 18:33