- Home /
How to select only the enemies in a range as targets
Okay, I have a list of enemies
public var enemies:GameObject[];
That include all of the enemies currently in the scene. I also have a list of targets:
public var targets:GameObject[];
Which I would like to include all of the objects between a certain range/distance(example: from 5 feet away and at a 45 degree angle each direction.)
How could I isolate only those objects? I am looking more for a method than the actual script, but if you feel obliged to do so, it will also be helpful.
Thanks,
Thor
The simple/slow approach would be to loop through each enemy and each target, and calculate the distance between them using Vector3.Distance(a,b)
. If its less than the range, its a valid target. This will operate at n*m (n^2) though, so only do this if you don't have many targets and enemies.
The more complex option includes using a QuadTree implementation, which essentially will help quickly query who is within the same square region as another point. Then you have less items to test distance with. But this is not exactly easy to implement. It is however a very common need in games, so information on it shouldn't be hard to find.
And as for your angle constraint:
float angle = Vector3.Angle( enemy.tranform.forward, target.transform.position - enemy.transform.position );
if (angle < angleOfView)
Target( target );
Hope this helps!
You can use the first idea above and optimize a little using sqr$$anonymous$$agnitude ins$$anonymous$$d of distance and dot product ins$$anonymous$$d of angle, you then avoid sqaure root and arcos for each of your calculation without losing accuracy.
Yes, agreed. These are nice optimizations that will help, but you'll need to know your maths. You lose simplicity, but gain performance. Good advice fafase.
Answer by Thor625 · Jul 02, 2013 at 04:58 PM
I ended up using Physics.OverlapSphere and system.collection.generic.list.
public var enemiesInRange : List.<GameObject> = new List.<GameObject>();
function Update(){
var hitColliders : Collider[] = Physics.OverlapSphere (transform.position, circleRadius);
for (var hit : Collider in hitColliders) {
if(hit.gameObject.tag == "Enemy"){
enemiesInRange.Add(hit.gameObject);
}
}
//From here you can use
var targets:GameObject[];
targets = enemies;
}
Answer by darthbator · May 29, 2013 at 09:06 PM
In this case I will normally attach some kind of trigger volume to my character so I can just add things as they pass into the trigger. Another way is to iterate over your array or targets and then use Vector3.distance and then check how "far" they are and then act on only the ones under a certain threshold.
Your answer
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to use Enum? 1 Answer
Pain in the ass 2 Answers