BloodAndGore/Assets/Scripts/Utils/Util.cs

48 lines
2.0 KiB
C#
Raw Permalink 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-22 18:59:36 +02:00
public static T GetClosestTo<T>(Transform Searcher, float radius, LayerMask layerMask, bool needsLineOfSight = false) where T : MonoBehaviour {
2019-08-04 17:35:24 +02:00
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-15 00:26:56 +02:00
if (Collider.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-22 18:59:36 +02:00
RaycastHit2D[] Hits = Physics2D.RaycastAll(Searcher.position, Delta.normalized, Distance, layerMask);
2019-08-04 17:35:24 +02:00
bool LineOfSightObstructed;
if (needsLineOfSight) {
LineOfSightObstructed = false;
foreach (RaycastHit2D Hit in Hits) {
2019-08-15 00:26:56 +02:00
if (Hit.collider != Collider && Hit.transform != Searcher &&
(Hit.rigidbody == null || Hit.rigidbody.transform != Searcher)) {
2019-08-04 17:35:24 +02:00
// 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
}
}