using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
[Serializable] public class UnityEventTranfromAndInt : UnityEvent<Transform, int> { }
[Serializable] public class UnityEventTranformArray : UnityEvent<Transform[]> { }
[Serializable] public class UnityEventTranform : UnityEvent<Transform> { }
public class Alertness : MonoBehaviour {
public int alertRadius;
public int attackRadius;
[Range(0, 360)] public float attackAngle;
#if UNITY_EDITOR
public Color alertColor = Color.blue;
public Color attackColor = Color.red;
#endif
private float angle;
private float distance;
private Vector3 from;
private float forwardAttackAngle;
private Transform tr;
private List<Transform> targets = new List<Transform>();
public UnityEventTranform onEnterAttackRadiusEvent =new UnityEventTranform();
public UnityEventTranformArray onTargetEnterEvent = new UnityEventTranformArray();
public UnityEventTranfromAndInt onTargetExitEvent = new UnityEventTranfromAndInt();
private void Awake()
{
tr = transform;
forwardAttackAngle = attackAngle / 2;
var collider = GetComponent<SphereCollider>();
if (collider == null)
{
collider = gameObject.AddComponent<SphereCollider>();
}
collider.center = Vector3.zero;
collider.isTrigger = true;
collider.radius = alertRadius;
}
private void Update()
{
foreach (var target in targets)
{
distance = Vector3.Distance(tr.position, target.position);
from = target.position - tr.position;
angle = Vector3.Angle(from, tr.forward);
if (distance <= attackRadius && angle <= forwardAttackAngle)
{
onEnterAttackRadiusEvent.Invoke(target);
}
}
}
private void OnTriggerEnter(Collider other)
{
targets.Add(other.transform);
onTargetEnterEvent.Invoke(targets.ToArray());
}
private void OnTriggerExit(Collider other)
{
targets.Remove(other.transform);
onTargetExitEvent.Invoke(other.transform, targets.Count);
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
var color = Handles.color;
Handles.color = alertColor;
Handles.DrawWireDisc(transform.position, transform.up, alertRadius);
Handles.color = attackColor;
var StartLine = Quaternion.Euler(0, -attackAngle / 2, 0) * this.transform.forward;
Handles.DrawSolidArc(this.transform.position, this.transform.up, StartLine, attackAngle, attackRadius);
Handles.color = color;
}
#endif
}