Hey guys, i’ve been trying to make FPS game with NPC can search and take cover. So far it’s working well with FindGameObjectsWithTag function which detect all game object (i made trigger) with “Cover” tag in it. I’ve used the code example in this scripting reference (FindClosestEnemy)
My question is what’s the best way i can detect if there is already other NPC which take the closest cover of the first NPC, and the first NPC will find another closest cover from there.
You could make NPCs that are taking cover to change the tag of the object they are behind: when a NPC select an object, it changes its tag, goes to it, takes cover and when leaving the cover, set back the original tag.
If you want to avoid objects with NPCs already taking cover, you can change the tag to anything that has not “cover” in it.
If you want to know each objects that are already “hosting” an NPC, you can change the tag to something like “CoverNPCTaken”
If you want the NPCs to know where are/is the player(s), change the tag to “CoverPlayerTaken”
Don’t know if it’s the best way, but that’s how i’d do it
public LayerMask layersToCheck;
public Vector3 coverCheckArea;
public bool occupied;
if(Physics.CheckBox (transform.position, coverCheckArea, layersToCheck)) {
Debug.Log("Somebody is in the cover");
occupied = true;
}
else {
Debug.Log("Cover is available");
occupied = false;
}
just an example the LayerMask can be used to set what layers u would want to check for so in this case just a Layer with Enemies/NPC’s
set the enemies onto this layer
i would leave Just what you see above as a seperate script upon each piece of cover, and then when your NPC does its search for cover Access this script and see if a bool for Occupied was true so
if(!coverObject.GetComponent<CoverChecker>().occupied) {
/// Space wasn't occupied do procedure for take cover
} else {
// space was occupied search for cover again and disclude this
// object from the check.
}