Feild of view only wokring in specific areas of the scene
Hi all, So I adapted a 3D field of view for an enemy to try and make it 2D, it appeared to all be working fine! Yay, I thought to myself, until it came to moving that enemy around the scene. What once was a perfect working FOV for an enemy completely stopped working and when I moved it to a different location it only partially worked. Tears began to well up and I nearly kicked my computer in it's stupid mocking face as I read though all of the different scripting instructions to make sure that I wasn't doing something stupid. Alas, I couldn't find anything. My gut tells me it has something to do with this line:
"float angle = Vector2.Angle(checkingObject.up, directionBetween);"
but I'm not sure why or how... Any help would be amazing! Ta Code - using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Fov : MonoBehaviour
{
public Transform player;
public float maxAngle;
public float maxRadius;
public bool isInFov;
void Start()
{
player = GameObject.FindWithTag("Player").transform;
}
private void Update()
{
isInFov = inFOV(transform, player, maxAngle, maxRadius);
}
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, maxRadius);
Vector2 fovLine1 = Quaternion.AngleAxis(maxAngle, transform.up) * transform.forward * maxRadius;
Vector2 fovLine2 = Quaternion.AngleAxis(-maxAngle, transform.up) * transform.forward * 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.DrawLine(transform.position, transform.forward * maxRadius);
}
public static bool inFOV(Transform checkingObject, Transform target, float maxAngle, float maxRadius)
{
Collider2D[] overlaps = new Collider2D[50];
int count = Physics2D.OverlapCircleNonAlloc(checkingObject.position, maxRadius, overlaps);
for(int i = 0; i < count + 1; i++)
{
if(overlaps[i] != null)
{
if(overlaps[i].transform == target)
{
Vector2 directionBetween = (target.position - checkingObject.position).normalized;
float angle = Vector2.Angle(checkingObject.up, directionBetween);
if(angle <= maxAngle)
{
RaycastHit2D hit = Physics2D.Raycast(checkingObject.position, target.position, maxRadius);
if(hit.transform == target)
{
return true;
}
}
}
}
}
return false;
}
}