I am trying to make a melee script that does damage to the closest enemy in the player’s field of view. I am using an OverlapSphere to detect potential colliders, iterating through an array of them, filtering out any not in the field of view, identifying the closest one, then a raycast to make sure no obstruction. I have been able to do damage so I know it’s working somewhat, but for the most part it wont damage even when right in front of the target. It seems I am not getting the right angles for the FOV check as it always registers 90 degrees when my crosshair is centered on the target when I assume should be 0. Am I missing something there or somewhere else or probably multiple places?
public class Sword : WeaponBase
{
public float attackDamage = 40f;
public float fovRange = 2f;
private Collider closestTarget;
private Vector3 dirToTarget;
float distance;
private int layerMask = 1 << 8; //select layer 8
[Range(0, 360)] public float fovAngle = 30.0f;
void Start()
{
attackCoolDown = 0.55f;
hand = "Right";
closestTarget = null;
distance = Mathf.Infinity;
}
public override void Attack()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, fovRange, layerMask); //get all the objects that could potentially be in field of view.
for (int i = 0; i < hitColliders.Length; i++) //make a loop to check whats there
{
dirToTarget = hitColliders*.transform.position - transform.position; // get target direction then check against field of view*
float angle = Vector3.Angle(dirToTarget, transform.forward);
Debug.Log("Target Angle = " + angle);
if (angle < fovAngle)
{
float curDistance = dirToTarget.sqrMagnitude;
if (curDistance < distance)
{
closestTarget = hitColliders*;*
distance = curDistance;
Debug.Log("Closest Target = " + closestTarget.gameObject.name);
}
}
else
{
return;
}
}
if (closestTarget != null)
{
// check to make sure nothing is obstructing
RaycastHit hit;
Physics.Raycast(fpsCam.transform.position, dirToTarget, out hit, layerMask);
{
IDamageable damageable = hit.transform.GetComponent(); // already checked for this above but not sure which one to get rid of yet
if (damageable != null)
{
Debug.Log("You hit " + damageable);
damageable.ApplyDamage(attackDamage);
closestTarget = null;
}
}
}
else
{
return;
}
}
}