Hi all,
Ultimately I am attempting to create similar lock-on functionality to this - where the closest target amongst an array of targets is chosen, perhaps a higher priority given to a target that the Centre of the screen is closest to - but that’s the end goal.
See my reference below.
Here is what my current code functionality is producing :
My problem :
It seems that the Vector3.Distance calculation is not correctly calculating which Target is closest. Oddly enough it seems to calculate a target that is further away as the nearest target rather than one that is directly closest.
Now I’m assuming the problem could one of a few things here but I’m not sure :
- That the visualization of the nearest target isn’t being updated enough and therefore displaying the incorrect target.
- That the math for distance calculation is not taking into account some key concept and therefore making the incorrect calculation.
- That my current basic code just isn’t correct.
My script is below :
void FindVisibleTargets()
{
visibleTargets.Clear();
nearestTarget = null;
Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, viewRadius, targetMask);
Transform nearestTargetInView = null;
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.forward, target.position);
if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))
{
visibleTargets.Add(target);
if (nearestTargetInView == null)
{
nearestTargetInView = target;
}
else if (nearestTargetInView != null)
{
float dstToPrevTarget = Vector3.Distance(transform.forward, nearestTargetInView.position);
Vector3 dir
if (dstToTarget > dstToPrevTarget)
{
nearestTargetInView = target;
}
}
nearestTarget = nearestTargetInView;
Debug.Log("Nearest target is " + nearestTarget.gameObject.name);
}
}
}
}
The above is from my Player Controller script, there is another Editor script that is soley for displaying the visuals on the editor and is simply taking the Publicly declared nearestTarget variable and adding a green circle around it.
Can anyone provide any guidance on what I am doing wrong here and perhpas also some future suggestions on how I’d manage prioritizing targets that are more central in the viewport over those whom are simply closer.
Thanks