I was wondering about how to find out if an object is able to see another object.
Well, I found this How can I check the line of sight to see if the player is visible to the enemy? and it works well.
But how should I implement something like partial obstacles on the way?
For example if I want to make a bush which makes it 10% harder to detect someone from behind it. And maybe with binoculars the detection handicap could be reduced to 5%.
What is the correct way to achieve this?
This is a kind of open ended question, so I’ve got a kind of open ended response.
Instead of using physics.raycast, use physics.raycastall.
It will return a list of everything along a line, but not in order. So, once you get a list of everything in the line, you’ll have to do some tests.
-
make sure the target is somewhere along the line.
-
Measure the distance to the target and store that.
-
Check every other object returned’s distance. If its less than the player distance, your ray hit it.
-
For each object you hit, check its type. If its a bush, add 5%, if its a wall, add 10%, etc.
Looking at the code you listed, I’m thinking it might be a good idea to use [Physics.RaycastAll][1] since you can receive ALL of the hits along your raycast (Note that order is not guaranteed.)
This means that your ray can go through bushes and glass. Here’s some untested code to describe what I’m thinking:
RaycastHit[] hits;
float gaurdAwareness = 1.0f; //This is a scalar to multiply with normal awareness
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
int i = 0;
while (i < hits.Length) {
RaycastHit hit = hits*;*
Obstacle obstcl = hit.transform.GetComponent();
if(obstcl ) {
gaurdAwareness -= obstcl.blockingPower; //how much the bush “blocks sight”
}
i++;
}
Basically, you get the “blocking power” of each obstacle between the “guard” and the “sneaker” to get the guard awareness which is then multiplied by the general awareness which is based upon distance, “sneaker” stance, and guard alertness level. You can also throw light levels and some scalar based on how long the guard has been “looking at the sneaker” in there.
If after all of these computations; the guards general awareness of the sneaker is higher than some threshold value, the “sneaker” is revealed. Otherwise, it remains hidden.
[1]: Unity - Scripting API: Physics.RaycastAll