BloodAndGore/Assets/Scripts/Utils/Util.cs
2019-08-14 20:05:16 +03:00

48 lines
2.0 KiB
C#

using UnityEngine;
namespace Saltosion.OneWeapon.Utils {
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 ||
(Collider.attachedRigidbody != null && Collider.attachedRigidbody.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;
}
public static int RandomValueBetween(int min, int max) {
int RollMax = max - min;
return (int)(min + Mathf.Min(Mathf.Floor(Random.value * (RollMax + 1)), RollMax));
}
}
}