BloodAndGore/Assets/Scripts/Utils/Util.cs

48 lines
2.0 KiB
C#
Raw Normal View History

2019-08-03 18:14:47 +02:00
using UnityEngine;
namespace Saltosion.OneWeapon.Utils {
2019-08-03 18:14:47 +02:00
public class Util {
2019-08-04 17:35:24 +02:00
public static T GetClosestTo<T>(Transform Searcher, float radius, bool needsLineOfSight = false) where T : MonoBehaviour {
Collider2D[] NearbyColliders = Physics2D.OverlapCircleAll(Searcher.position, radius);
2019-08-03 18:14:47 +02:00
float LowestDistance = float.PositiveInfinity;
T FoundTarget = null;
foreach (Collider2D Collider in NearbyColliders) {
2019-08-14 18:05:41 +02:00
if (Collider.gameObject == Searcher.gameObject ||
(Collider.attachedRigidbody != null && Collider.attachedRigidbody.gameObject == Searcher.gameObject)) {
2019-08-04 17:35:24 +02:00
continue;
}
Vector2 Delta = (Collider.transform.position - Searcher.position);
float Distance = Delta.magnitude;
2019-08-03 18:14:47 +02:00
T TargetComponent = Collider.GetComponent<T>();
2019-08-04 17:35:24 +02:00
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) {
2019-08-03 18:14:47 +02:00
LowestDistance = Distance;
FoundTarget = TargetComponent;
}
}
return FoundTarget;
}
2019-08-14 19:05:16 +02:00
public static int RandomValueBetween(int min, int max) {
int RollMax = max - min;
return (int)(min + Mathf.Min(Mathf.Floor(Random.value * (RollMax + 1)), RollMax));
}
2019-08-03 18:14:47 +02:00
}
}