BloodAndGore/Assets/Scripts/Util/Util.cs

42 lines
1.7 KiB
C#

using UnityEngine;
namespace Saltosion.OneWeapon {
public class Util {
public static T GetClosestTo<T>(Transform Searcher, float radius, bool needsLineOfSight = false) where T : MonoBehaviour {
Collider2D[] NearbyColliders = Physics2D.OverlapCircleAll(Searcher.position, radius);
float LowestDistance = float.PositiveInfinity;
T FoundTarget = null;
foreach (Collider2D Collider in NearbyColliders) {
if (Collider.gameObject == Searcher.gameObject) {
continue;
}
Vector2 Delta = (Collider.transform.position - Searcher.position);
float Distance = Delta.magnitude;
T TargetComponent = Collider.GetComponent<T>();
RaycastHit2D[] Hits = Physics2D.RaycastAll(Searcher.position, Delta.normalized, Distance);
bool LineOfSightObstructed;
if (needsLineOfSight) {
LineOfSightObstructed = false;
foreach (RaycastHit2D Hit in Hits) {
if (Hit.collider != Collider && Hit.transform != Searcher) {
// Hit something between the target and the searcher
LineOfSightObstructed = true;
break;
}
}
} else {
LineOfSightObstructed = false;
}
if (TargetComponent != null && !LineOfSightObstructed && Distance < LowestDistance) {
LowestDistance = Distance;
FoundTarget = TargetComponent;
}
}
return FoundTarget;
}
}
}