NPC finding cover system

So I’ve working on a system that makes an NPC find and move to cover relative to the nearest player’s position. The moving to cover works fine but finding cover is difficult. I would like to know what would be the most effective way to locate the nearest cover from the NPC. I would also like to know how would I go about allowing the NPC to use cover standing or crouched based on height. (Note for a cover to be valid the NPC must be able to peek off it and get a clear line of sight to the player). Any help is appreciated.

1 Like

You can use something like a CollectionService to tag different kind of cover for example

image

The Yellow outline cover has a “Low” tag
The Green outline cover has a “High” tag

You can also tag the object that can be used as cover with the “cover” tag
This way the NPC can differentiate the map part and the cover part
Better yet. Because now the part has been tagged you can making so the NPC will be more likely to hide in a full cover which offers more protection

Thank for the reply but I don’t really want to manually tag all possible cover. Is there any way for the NPC to determine objects that can be used for cover in front of it without predetermining the possible cover?

you can use Vector3.Magnitude to check if the object is high enough to be considered half or full cover

I made a really basic find cover system a while back, its certainly not the most efficient way but it meant I didn’t have to go and tag stuff all over my game.

Basically the way it works is it would generate points in a circle around the NPC. It would then raycast from those points to wherever the danger is (e.g. enemy player or another NPC), if the raycast failed it meant there was no line of sight and therefore it was a ‘place of cover’.

If it couldn’t find any places for cover, it would increase the radius of the points in the circle around the npc and try again. Raycasts are cheap so this isn’t that bad. I would increase the radius about 4 studs each time.

You of course set an upper limit, say a radius of 10 studs. You can also get better accuracy if instead of using 1 raycast to check if its cover, if you instead use a few in more of a grid formation (or maybe use blockcast or spherecast) so that you can be more sure it covers the entire body.

You can also use raycasts to simply check if the cover is short or tall if you want them to crouch or stand.

This worked really well for me, hope it does for you too (: