- Home /
Help with FOV script.
I need help with what appears to be a simple problem which I can't seem to fix.
If I have the enemy looking at you, he follows you, however, if you're out of his view, he stops.
Heres the script:
void FindVisibleTargets()
{
visibleTargets.Clear();
Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, viewRadius, targetMask);
for (int i = 0; i < targetsInViewRadius.Length; i++)
{
Transform target = targetsInViewRadius[i].transform;
Vector3 dirToTarget = (target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, dirToTarget) < viewAngle / 2)
{
float dstToTarget = Vector3.Distance(transform.position, target.position);
if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))
{
visibleTargets.Add(target);
Debug.Log("Follow");
}
else
{
Debug.Log("Stop");
}
}
}
}
It's not saying "Stop" in the console once the character is out of its view. Can anyone help me with this?
Answer by DawdleDev · Jul 09, 2018 at 06:56 PM
The code you wrote basically says, "if the other object is further than the distance to the other object, print stop." As you can imagine, this isn't going to work. You need to make it use, "if the other object is further than the distance I can see, print stop." Here's a revised code:
// This goes somewhere up at the beginning of your code
public const float VisibleReach = *Some Number*
.
for (int i = 0; i < targetsInViewRadius.Length; i++)
{
Transform target = targetsInViewRadius[i].transform;
Vector3 dirToTarget = (target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, dirToTarget) < viewAngle / 2)
{
if (!Physics.Raycast(transform.position, dirToTarget, VisibleReach, obstacleMask))
{
visibleTargets.Add(target);
Debug.Log("Follow");
}
else
{
Debug.Log("Stop");
}
}
}
The script is working now, thank you. I would just add that if the character moved out of the radius such as behind the enemy right after its seen, he doesn't follow neither does he stops. I am going to try and find a way to fix that for now.
Your answer
![](https://koobas.hobune.stream/wayback/20220612170346im_/https://answers.unity.com/themes/thub/images/avi.jpg)