- Home /
focusing on a unit during unit detection in an RTS
Hey guys, I have an enemy unit which detects a player unit within 10 distance and then goes to its position. The problem is, when there are other units within 10 units distance, the enemy unit switches back and forth between the units. Is there a way I can make my enemy unit focus on the position of a single controlled player unit instead of all of them? I want to eventuall make it so the enemy chooses the nearest unit. Thanks, Code is posted here:
IEnumerator distanceBoolToggle(){ //included in the coroutine to save memory
while (numeratorBool==false) {
for (int i=0; i<UnitsList.Count; i++) { //this iterates through my list of player-unit objects
float distance = Vector3.Distance (transform.position, UnitsList [i].transform.position);
//this calculates the distance from one player-unit to enemy unit
if (distance <= 10) { //if the distance is less than 10 between player unit and enemy unit
GameObject playerObject = UnitsList [i]; //creates an object for that specific player unit
AstarAI playerObjectDetection = playerObject.GetComponent<AstarAI> (); //gets astarai code for that unit
targetPosition = playerObjectDetection.transform.position; //sets the enemy position to the pos of the player unit
float distanceToTargetPos = Vector3.Distance (transform.position, targetPosition); //finds distance between the two units
if (distanceToTargetPos > 3) {
seeker.StartPath (transform.position, targetPosition, OnPathComplete); //if distance is more than 3 than travel towards its destination
}
}else{
}
}
yield return new WaitForSeconds (1f);
}
}
For readability put comments on the line before the code they refer to.
Answer by Kiwasi · May 26, 2014 at 12:25 AM
I would suggest only going through the list if there is no current target.
Something like this (meta code only)
Define a private GameObject currentTarget
If currentTarget = null or currentTarget distance > ten
Run your code to find and assign a new currentTarget
An alternative is to use a trigger and create a private list on the enemy that grabs each player unit as it comes into range and deletes it as it leave range. This could make your script much cheaper to run as it only has to run through the units that are close, rather than every player unit on the map.
I'd also suggest using Vector3.sqrMagnitude instead of Vector3.Distance. Much faster for straight comparisons as there is no square root involved.
Your answer
Follow this Question
Related Questions
Help Calculating Shortest Total Distance Travelled By a Combination of Objects 0 Answers
How to forbid an NPC to move diagonally using Character Controller? 1 Answer
swipe distance detection dont work 2 Answers
Game NPC "Guide" Movement (Much like Navi from Zelda) 1 Answer
Help with 2D AI scripting 2 Answers