using System.Collections; using System.Collections.Generic; using UnityEngine; public class Detection : MonoBehaviour { private Vector2 detectionRange; private BoxCollider2D _collider; public Rect DetectionRectangle { get { if (!_collider) _collider = GetComponent(); var bounds = _collider.bounds; return new Rect(bounds.min - transform.position, bounds.size); } } [SerializeField] private Entity _entityLinked; protected virtual void Start() { _collider = GetComponent(); detectionRange = _collider.size; } void ResizeCollider() { if (!EntityLinked) return; var multiplier = EntityLinked.RangeMultiplier; var size = _collider.size; size.x = detectionRange.x * multiplier.x; size.y = detectionRange.y * multiplier.y; _collider.size = size; var offset = _collider.offset; if (offset == Vector2.zero) return; offset.x = Mathf.Sign(offset.x) * size.x / 2; _collider.offset = offset; } //If it's a projectile damage > 0 private int _projectileDamage = 0; private float _distanceMin = 100f; protected virtual void Update() { ResizeCollider(); } void OnTriggerEnter2D(Collider2D other) { //Projectiles detection + damage deal if(_entityLinked != null) { if(_projectileDamage > 0 && other.gameObject.GetComponent() == _entityLinked) { _entityLinked.Hit(_projectileDamage); //Kill if no hp if(other.gameObject.GetComponent().Hp <= 0) { other.gameObject.GetComponent().Death(); } _entityLinked = null; } } } void OnTriggerStay2D(Collider2D other) { if(_entityLinked != null && _projectileDamage == 0) { //Detect the enemy and inform the Ally if (other.gameObject.tag == "Opponent" && _entityLinked.gameObject.tag == "Ally") { if(other.gameObject.transform.position.x <= _distanceMin) { _distanceMin = other.gameObject.transform.position.x; _entityLinked.IsEnemyDetected = true; _entityLinked.Enemy = other.gameObject.GetComponent(); } } //Detect the enemy and inform the Opponent if (other.gameObject.tag == "Ally" && _entityLinked.gameObject.tag == "Opponent" ) { if(other.gameObject.transform.position.x <= _distanceMin) { _distanceMin = other.gameObject.transform.position.x; _entityLinked.IsEnemyDetected = true; _entityLinked.Enemy = other.gameObject.GetComponent(); } } if(_entityLinked.Enemy == null && _distanceMin != 100f) { _distanceMin = 100f; } } } void OnTriggerExit2D(Collider2D other) { if(_entityLinked != null) { if(_projectileDamage == 0) { if ((other.gameObject.tag == "Opponent" && _entityLinked is Ally) || (other.gameObject.tag == "Ally" && _entityLinked is Opponent)) { _entityLinked.IsEnemyDetected = false; } } } } //Getter and Setter public Entity EntityLinked { get { return _entityLinked; } set { _entityLinked = value; } } public int ProjectileDamage { get { return _projectileDamage; } set { _projectileDamage = value; } } }