I'm learning Unity game development and I cannot properly fix the AI of my enemies. My game is a simple top-down shooter and I do not want my enemies to overlap on each other. I have decided to cast a ray in the front of an enemy to check, whether there is an obstacle (another enemy) or not.
Enemies have got a rigidbody2d and box collider. They are casting a ray in a proper direction (checked by Debug.Drawray()) but they do not detect any hit until they stop at standing in the same positions. (i.e. They are moving to my position and as soon as they stop, the hit is detected)
I am wondering what am I doing wrong and I cannot get this working properly for the past few days. Maybe someone has got a clue what could be wrong?
Code from a single enemy manager:
Vector2 startPos = transform.position;
Vector2 endPos = transform.right * 10; // transform right as they are rotated by 90 degrees to the right.
Debug.DrawRay(startPos, endPos);
RaycastHit2D hit = Physics2D.Raycast(startPos, endPos, 10f);
if (hit && hit.collider.gameObject != gameObject)
{
Debug.Log(hit.transform.name + " was hit");
}