Hello Everyone, as the title suggests, I’m having trouble coding a script in C# that will give my enemy ai a “field of view”. This view will be in a shaped as a circle but have a cone that follows the direction of the enemy as it moves. So far, I’ve followed this great tutorial on YouTube but it seems to only work for 3D and I need this for a 2D top down game.
[YouTube Video Link][1]
[GitHub Script/Sources][2]
So far I’ve managed to tweak the code a bit so the Gizmos that are drawing the raycasts can draw them at the correct angles I was looking for.
public class LineOfSight_Rotation : MonoBehaviour
{
public Transform player;
public float maxAngle;
public float maxRadius;
private bool isInFov = false;
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, maxRadius);
Vector3 fovLine1 = Quaternion.AngleAxis(maxAngle, transform.forward) * transform.up * maxRadius;
Vector3 fovLine2 = Quaternion.AngleAxis(-maxAngle, transform.forward) * transform.up * maxRadius;
Gizmos.color = Color.blue;
Gizmos.DrawRay(transform.position, fovLine1);
Gizmos.DrawRay(transform.position, fovLine2);
if (!isInFov)
Gizmos.color = Color.red;
else
Gizmos.color = Color.green;
Gizmos.DrawRay(transform.position, (player.position - transform.position).normalized * maxRadius);
Gizmos.color = Color.black;
Gizmos.DrawRay(transform.position, transform.up * maxRadius);
}
public static bool inFOV(Transform checkingObject, Transform target, float maxAngle, float maxRadius)
{
Collider[] overlaps = new Collider[10];
int count = Physics.OverlapSphereNonAlloc(checkingObject.position, maxRadius, overlaps);
for (int i = 0; i < count + 1; i++)
{
if (overlaps *!= null)*
{
if (overlaps*.transform == target)*
{
Vector3 directionBetween = (target.position - checkingObject.position).normalized;
directionBetween.y *= 0;
float angle = Vector3.Angle(checkingObject.forward, directionBetween);
if (angle <= maxAngle)
{
Ray ray = new Ray(checkingObject.position, target.position - checkingObject.position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, maxRadius))
{
if (hit.transform == target)
return true;
}
}
}
}
}
return false;
}
private void Update()
{
isInFov = inFOV(transform, player, maxAngle, maxRadius);
}
}
However, when I try to follow the last step of the video which explains how to do the actual detection of the player it doesn’t work and the player line (red), doesn’t turn green within range. Sooo… this is my main problem thus far and all help would be appreciated!
_[1]: (04) Stealth Game - Field of View (Unity, C#) - YouTube
_[2]: https://github.com/AJTech2002/Stealth-Series/blob/master/Parts/Stealth%20Game%20Part%204/Assets/Scripts/FOVDetection.cs*_