I have been trying to wrap my head arround this for HOURS and it just isnt making any sense to me. I want the turret to stop targeting the target once it is out of range, and it does for the first target but when it locks onto the second target it just stays locked forever. Please help!
if(target != null){
if(Vector3.Distance(this.transform.position, target.transform.position) < turretRange){
Vector3 targetPostition = new Vector3( target.transform.position.x, turretHead.transform.position.y, target.transform.position.z ) ;
turretHead.transform.LookAt(targetPostition + target.GetComponent<Rigidbody>().velocity);
lr.SetPosition(0, turretHead.transform.position);
lr.SetPosition(1, target.transform.position);
}
else{
lr.SetPosition(0, new Vector3 (1000,1000,1000));lr.SetPosition(1, new Vector3 (1000,1000,1000));
}
}
//Target Finding
targets = GameObject.FindGameObjectsWithTag("Target").ToList();
target = closestTarget;
if(targets != null){
for(int i = 0; i <= targets.Count; i++){
if(Vector3.Distance(targets[i].transform.position, gameObject.transform.position) > turretRange){
targets.Remove(targets[i]);
return;
}
if(closestTarget == null){
closestTarget = targets[i].gameObject;
}
if(Vector3.Distance(closestTarget.transform.position, gameObject.transform.position) >= (Vector3.Distance(targets[i].transform.position, gameObject.transform.position))){
closestTarget = targets[i].gameObject;
}
if(Vector3.Distance(closestTarget.transform.position, gameObject.transform.position) < (Vector3.Distance(targets[i].transform.position, gameObject.transform.position))){
return;
}
}
}
distanceToTarget = (float)Vector3.Distance(target.transform.position, gameObject.transform.position);
Also, distanceToTarget is always zero, IDK why.