using System.Collections; using UnityEngine; using UnityEngine.AI; namespace Ai { [RequireComponent(typeof(NavMeshAgent))] public class TargetingEnemy : MonoBehaviour { [SerializeField, HideInInspector] private Body _body; [SerializeField] protected float _visibilityDistance; [SerializeField] protected NavMeshAgent _agent; [SerializeField] protected Gun[] _guns; [SerializeField] private int _bodyDamage; public GameObject Lock { get; set; } public bool IsTargetable { get { return _body.IsTargetable; } } private bool _hasGun; public void OnEnable() { if (_body != null) AiController.Instance.TargetingEnemies.Add(this); _hasGun = _guns != null && _guns.Length > 0; Init(); } public void OnDisable() { if (AiController.Instance != null) AiController.Instance.TargetingEnemies.Remove(this); StopAllCoroutines(); _character = null; } protected virtual void Init(){} public virtual void SetGuns(Vector3 playerPosition) { if (!_hasGun) return; foreach (var gun in _guns) { if (gun == null) continue; gun.CanShoot = Vector3.Distance(playerPosition, transform.position) <= _visibilityDistance; } } public virtual void Proceed(Vector3 playerPosition) { if (Vector3.Distance(playerPosition, transform.position) > _visibilityDistance) return; _agent.SetDestination(playerPosition); } private void OnCollisionEnter(Collision other) { var player = other.gameObject.GetComponent(); if (player != null) Proceed(player); } private void OnTriggerEnter(Collider other) { var player = other.gameObject.GetComponent(); if (player != null) Proceed(player); } private void OnCollisionExit(Collision other) { var player = other.gameObject.GetComponent(); if (player == null) return; StopAllCoroutines(); _character = null; } private void OnTriggerExit(Collider other) { var player = other.gameObject.GetComponent(); if (player == null) return; StopAllCoroutines(); _character = null; } private void Proceed(MainCharacter character) { _character = character; float abilityVal = GlobalsVar.gMainAbilities.GetAbilityValueByType(Ability.MainAbilityType.ADD_ARMOR_SHOT); float damage = _bodyDamage - _bodyDamage * (abilityVal / 100f); character.TakeDamage((int)damage); StartCoroutine(TimeCheck()); } private MainCharacter _character; private IEnumerator TimeCheck() { yield return new WaitForSeconds(0.3f); if (_character != null) { StartCoroutine(TimeCheck()); float abilityVal = GlobalsVar.gMainAbilities.GetAbilityValueByType(Ability.MainAbilityType.ADD_ARMOR_SHOT); float damage = _bodyDamage - _bodyDamage * (abilityVal / 100f); _character.TakeDamage((int)damage); } } private void OnValidate() { if (_agent == null) _agent = GetComponent(); if (_body == null) _body = GetComponent(); } } }