- Home /
Making an AI Flee
private void Flee(List<GameObject> objectsToFlee)
{
Vector3 fleeVector = Vector3.zero;
foreach (GameObject obj in objectsToFlee)
fleeVector += (obj.transform.position + other obj that are in range.transform.position) / number of obj in range
}
Movetwards(- fleeVector);
} anyone know how to say this? like how could i say all obj in range with more mass than this gameobject added together then divided by the number of those gameobjects. Im making an Ai and I want it to run away from any gameobject with more mass than itself. its not that hard to make it run away if one enemy comes in range, but if 2 or more enemies come in range, i need it to find the best way to run away
Answer by SpeakBeaver · Aug 10, 2018 at 07:15 PM
You can use Physics.OverlapSphere with your object position and a range, and compute your condition by using the array given by this method to know if you need to move away
Hope it helps ! Good Luck for your AI
currently i calculate the distance of each gameobject on the map, and any get to close it will run away but if multiple come in range i just need it to add them together, and divide it by the the number that are in range, the runaway from that point
I don't understand what you mean by "add them together and divide it", what do you want to add ? mass , scaling , other properties ?
Because when multiple come in range you have all the information needed if you already the range of each GameObject.
so how can i use that info to make it runaway, from multiple gameobjects at the same time?
if you want to know the number to divide by, you can create an empty object, who check range for each GameObject (getting using tag for example) and by increment a variable used in the method call who divide objects interested
Answer by Jdogmaster · Aug 10, 2018 at 08:40 PM
private void Flee(List<GameObject> objectsToFlee)
{
Vector3 fleeVector = Vector3.zero;
foreach (GameObject obj in objectsToFlee)
{
fleeVector += (obj.transform.position - this.transform.position);
}
fleeVector /= objectsToFlee.Count;
Debug.Log("Run");
MoveTowards(-fleeVector);
}
private void MoveTowards(Vector3 target)
{
transform.position = Vector3.MoveTowards(transform.position, target, moveSpeed * Time.deltaTime);
}
i tried this, it kind works but not that great
Why it's not that great ?
Juste an idea : Ins$$anonymous$$d of working with position, you can work with forces and a RigidBody. Try to compute the vector of the direction where to flee and give to the force this vector until the object arrives to the target. $$anonymous$$aybe it's gonna work better.
Your answer
Follow this Question
Related Questions
foreach loop stops at first item 1 Answer
Ai dodge bullets 3 Answers
Why do the AI get caught on trees? 0 Answers
Help With Add and Remove on a loop 2 Answers
my foreach loop and condition wont work 0 Answers