Enemy detects obstacle in front of its path and switches walking lane once it is close

I have waves of enemy spawning and walking from left to right, i want them to witch another lane if they detect an obstacle directly in front of them. they dont have to turn or anything just magicly move to a free lane nedxt to them and keep walking straight. can anyone help me please?
thanks in advance!

Hi!

Here is example how it could look like:

/* If Linecast hit collider within 1 unit to the right from transform.position */
if(Physics.Linecast(transform.position, transform.position + Vector3.right))
{
    if(!Physics.Linecast(transform.position + Vector3.up, transform.position + Vector3.up + Vector3.right))
    {
        /* If lane above is free then move up */
    }
    else if(!Physics.Linecast(transform.position + Vector3.down, transform.position + Vector3.down + Vector3.right))
    {
        /* Otherwise check if lane below is free then move down */
    }
    else
    {
        /* Otherwise if both lanes have collision on their way then do something else */
    }
}

Keep in mind that this is only an example: here Vector3.up and Vector3.down represents distance between top and bottom lane, so by adding it to transform.position we checking next lane, you would like to change it depending on where your lanes located in world and if it is 3D or 2D.


Overall logic is that we are casting Linecast from our transform.position to the world right (Vector3.right) and if it hits something - means that it will return TRUE then we have some Collider on your path, so we check other lanes and if they are empty we move accordingly or if they also have Collider we might specify what we do in the last else statement.

Keep in mind that if it will hit another enemy Collider it will as well search for free lanes so you either can separate enemy and obstacles by Layers and specify layer in Linecast or separate them by Tags and check CompareTag of hitted by Linecast object.


Here you can find more detailed info about Physics.Linecast: Unity - Scripting API: Physics.Linecast

Here you can find more detailed info about the same feature, but if you are working in 2D space: Unity - Scripting API: Physics2D.Linecast


Hope it helps.

i think i figured it out thank you very much