Collider[] rangeChecks = Physics.OverlapSphere(transform.position, radius, targetMask);
if (rangeChecks.Length != 0)
{
Transform target = rangeChecks[0].transform;
Vector3 directionToTarget = (target.position - transform.position).normalized;
//DrawDebugRays();
bool withinXZPlane = Mathf.Abs(VectorUtils.AngleOffAroundAxis(directionToTarget, transform.forward, transform.up)) < angle / 2;
bool withinYZPlane = Mathf.Abs(VectorUtils.AngleOffAroundAxis(directionToTarget, transform.forward, transform.right)) < angle / 2;
print(Mathf.Abs(VectorUtils.AngleOffAroundAxis(directionToTarget, transform.forward, transform.right)) + " < " + (angle / 2));
if (withinXZPlane && withinYZPlane)
{
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (!Physics.Raycast(transform.position, directionToTarget, distanceToTarget, obstructionMask))
canSeeTarget = true;
else
canSeeTarget = false;
}
else
canSeeTarget = false;
}
else if (canSeeTarget)
canSeeTarget = false;
//in another script
using UnityEngine;
public static class VectorUtils
{
public static float AngleOffAroundAxis(Vector3 v, Vector3 forward, Vector3 axis)
{
Vector3 right = Vector3.Cross(axis, forward).normalized;
forward = Vector3.Cross(right, axis).normalized;
return Mathf.Atan2(Vector3.Dot(v, right), Vector3.Dot(v, forward)) * MathUtil.RAD_TO_DEG;
}
}
Source: https://www.youtube.com/watch?v=j1-OyLo77ss
Source: https://forum.unity.com/threads/vector3-angle-on-relative-axis.381886/
//used parts from both sources for any variables that are not
//declared locally, just declare them as global variables and
//use SerializeField if you want. It may be beneficial to look at
//the sources to see where they were going with their code