- Home /
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:
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!
Answer by Eudaimonium · Jun 07, 2016 at 12:33 AM
You're trying to code up an already existing feature.
Try researching the topics related to Navmesh and AI Agents:
http://docs.unity3d.com/Manual/nav-CreateNavMeshAgent.html
http://docs.unity3d.com/Manual/nav-CreateNavMeshObstacle.html
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 :D ), 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.
Your answer
Follow this Question
Related Questions
Obtain angle from given rotation 1 Answer
How to detect if player is facing towards enemy's back 2 Answers
problem with vector3.Angle with a fixed joint 2 Answers
Vector3.SignedAngle wrong direction when crossing the 0 point 1 Answer
How Do I accurately rotate a player 180 degrees about the Z axis? 1 Answer