// ignoreNonPreferrential // In a sphere with the radius of range, find all enemy units and pick one to target List <ITargetable> ScanForTargets(bool ignoreNonPreferred) { Collider[] cols = Physics.OverlapSphere(transform.position, range, gameRules.targetLayerMask); List <ITargetable> targs = new List <ITargetable>(); for (int i = 0; i < cols.Length; i++) { ITargetable targ = GetITargetableFromCol(cols[i]); if (IsNull(targ)) // No targetable found { continue; } if (targs.Contains(targ)) // Ignore multiple colliders for one targetable { continue; } if (targ.GetTeam() == parentUnit.GetTeam()) // Can't target allies { continue; } if (!targ.GetVisibleTo(parentUnit.GetTeam())) // Must be visible to this team { continue; } // Can ignore non-preferred targets altogether (used when searching for a better target) if (ignoreNonPreferred && targ.GetTargetType() != preferredTargetType) { continue; } // The list of colliders is created by intersection with a range-radius sphere, but the center of this unit can still actually be out of range, leading to a target which cannot be shot at if (!IsValid(targ)) { continue; } targs.Add(targ); } // Sort by distance and target type targs.Sort(delegate(ITargetable a, ITargetable b) { return(ComparisonWeight(a) .CompareTo( ComparisonWeight(b))); }); return(targs); }
bool IsValid(ITargetable potentialTarget) { // Valid distance float sqrDistance = !IsNull(potentialTarget) ? (potentialTarget.GetPosition() - parentUnit.transform.position).sqrMagnitude : 0; // Check distance between us and the target // TODO: Maybe check from the parent unit's position? // Valid direction Vector3 dir = !IsNull(potentialTarget) ? CalcAdjDirection(potentialTarget) : transform.forward; // direction used elsewhere to check if aimed at target or not bool valid = false; // Have target, its in range, the look rotation is within limits, it is visible to our team if (!IsNull(potentialTarget) && sqrDistance <= range * range && ValidRotationHorizontal(CalcLookRotation(dir)) && potentialTarget.GetVisibleTo(parentUnit.GetTeam())) { valid = true; } else { valid = false; } return(valid); }