Need help setting a vector behind a character

I am trying to get my AI to run away from the player if he is too close to them. I want my program to create an point behind the AI and check if they can walk to that point. Here is an diagram of what I am after:

71613-untitled.png

My code only seems to work if the AI’s origin is at zero. How can I get this to work?
Here is my code so far:

Vector3 SetRetreatPosition()
    {
        Vector3 temp = Vector3.zero;
        LayerMask layerMask = (1 << LayerMask.NameToLayer("Blockade") | 1 << LayerMask.NameToLayer("Environment")); // ignore all but blockades and environment

        behindAngle = Vector3.Dot(transform.position, transform.position - transform.forward * 5);

        for (int i = 0; i < 180; i++)
        {
            for (int j = -1; j <= 1; j += 2)
            {
                temp = transform.position - (Quaternion.AngleAxis(behindAngle - (i * j), transform.up) * transform.forward * 5);

                if (!Physics.Linecast(transform.position, temp, layerMask))
                    return temp;
            }
        }

        return transform.position - (transform.forward * 5);
    }

Any help would be appreciated. Thank you in advance!

You’re trying to code up an already existing feature.

Try researching the topics related to Navmesh and AI Agents:

In short, a “navmesh” is a calculated object which basically tells any AI where are all the possible positions it can be at, and how to get there.

Your approach is very inefficient. For starters, your “j” loop will really only run once since it goes from -1 to 1 (but increments by 2 :smiley: ), and you are doing 180 Physics linecasts in a single object’s Update loop. If you were to expand that to 10 AI enemies, you’d start seeing performance drops even on non-mobile hardware I believe.