- Home /
Question by
Kek_Kek · Jul 03, 2018 at 07:57 PM ·
fovfieldofviewfield of vision
Help with Ai Field of view Script
I have a field of view script for an enemy. The script goes if the Player is seen and is close to the guard example 10 feet away, the enemy would walk towards him, but if the player is seen and is farther away such as 30 feet away, the enemy would run. Everything works except that if the player is close to the enemy, it states that he is close and far at the same time. Is there any way to make it so it states he is close.
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FieldOfView : MonoBehaviour
{
public GameObject TitanControl;
public float delay;
[Range(0, 360)]
public float viewRadiusMax;
[Range(0,360)]
public float viewRadius;
[Range(0, 360)]
public float viewAngle;
public LayerMask targetMask;
public LayerMask obstacleMask;
[HideInInspector]
public List<Transform> visibleTargets = new List<Transform>();
public float meshResolution;
public int edgeResolveIterations;
public float edgeDstThreshold;
public MeshFilter viewMeshFilter;
Mesh viewMesh;
private bool far;
private bool stop;
public bool close;
void Start()
{
viewMesh = new Mesh();
viewMesh.name = "View Mesh";
viewMeshFilter.mesh = viewMesh;
StartCoroutine("FindTargetsWithDelay", .2f);
}
IEnumerator FindTargetsWithDelay()
{
while (true)
{
yield return new WaitForSeconds(delay);
FindVisibleTargets();
FindVisibleTargetsFar();
}
}
void FindVisibleTargets() // Close
{
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("Close");
}
else
{
Debug.Log("NotSeen");
}
}
}
}
void FindVisibleTargetsFar() // Far Away
{
visibleTargets.Clear();
Collider[] targetsInViewRadiusFar = Physics.OverlapSphere(transform.position, viewRadiusMax, targetMask);
for (int i = 0; i < targetsInViewRadiusFar.Length; i++)
{
Transform target = targetsInViewRadiusFar[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("far");
}
else
{
Debug.Log("NotSeen");
}
}
}
}
}
Comment