2 Enemies chases each other

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

Hi, I’m having a problem with my enemies, when there are 2 enemies, they both chase each other instead of the player.

My code for the enemies:

extends KinematicBody2D

var run_speed = 25
var velocity = Vector2.ZERO
var player = null

func _physics_process(delta):
    velocity = Vector2.ZERO
    if player:
        velocity = position.direction_to(player.position) * run_speed
    velocity = move_and_slide(velocity)

func _on_Alert_body_entered(body):
    player = body

func _on_Alert_body_exited(body):
    player = null
:bust_in_silhouette: Reply From: Inces

They collide with each other and set themselves as player at the moment of collision.
Prevent enemies from colliding with each other, or make sure enemy class is an exception when choosing chase target.

So what changes do I have to make in the code?

CatboyCodes | 2022-07-20 21:11

You would better do it in editor. Make player collision layer 0, and enemies collision layer 1, and enemies collision mask only 0.

Inces | 2022-07-21 14:56

ok, let me see if it works

CatboyCodes | 2022-07-21 20:10