BloodAndGore/Assets/Scripts/Utils/Util.cs

48 lines
2.0 KiB
C#

using UnityEngine;
namespace Saltosion.OneWeapon.Utils {
public class Util {
public static T GetClosestTo<T>(Transform Searcher, float radius, LayerMask layerMask, 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, layerMask);
bool LineOfSightObstructed;
if (needsLineOfSight) {
LineOfSightObstructed = false;
foreach (RaycastHit2D Hit in Hits) {
if (Hit.collider != Collider && Hit.transform != Searcher &&
(Hit.rigidbody == null || Hit.rigidbody.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;
}
public static int RandomValueBetween(int min, int max) {
int RollMax = max - min;
return (int)(min + Mathf.Min(Mathf.Floor(Random.value * (RollMax + 1)), RollMax));
}
}
}