Advertisement
_LINKI

EnemyUnityExample

Mar 29th, 2021
882
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. [RequireComponent(typeof(Rigidbody2D))]
  4. [RequireComponent(typeof(Health))]
  5. public class Enemy : MonoBehaviour
  6. {
  7.     public static Enemy Create(Vector2 position)
  8.     {
  9.         var enemyPrefab = Resources.Load<Enemy>(nameof(Enemy));
  10.         return Instantiate(enemyPrefab, position, Quaternion.identity);
  11.     }
  12.  
  13.     [Header("Parameters")]
  14.     [SerializeField] private float _speed;
  15.     [SerializeField] private int _damage;
  16.     [SerializeField] private float _targetMaxRadius;
  17.     [SerializeField] private float _findTargetsCooldown;
  18.  
  19.     public Health Health { get; private set; }
  20.  
  21.     private Rigidbody2D _rigidbody;
  22.     private Vector2 _target;
  23.  
  24.     private void Start()
  25.     {
  26.         Health = GetComponent<Health>();
  27.         Health.OnDeadEvent += OnDead;
  28.  
  29.         _rigidbody = GetComponent<Rigidbody2D>();
  30.         InvokeRepeating(nameof(LookForTargets), 0, _findTargetsCooldown);
  31.     }
  32.     private void OnDead() => Destroy(gameObject);
  33.  
  34.     private void FixedUpdate()
  35.     {
  36.         var direction = (_target - (Vector2)transform.position).normalized;
  37.         _rigidbody.velocity = direction * _speed;
  38.     }
  39.     private void LookForTargets()
  40.     {
  41.         _target = Vector2.zero;
  42.  
  43.         var colliders = Physics2D.OverlapCircleAll(transform.position, _targetMaxRadius);
  44.         foreach (var collider in colliders)
  45.         {
  46.             if (collider.TryGetComponent(out Building building))
  47.             {
  48.                 var distance1 = Vector2.Distance(transform.position, _target);
  49.                 var distance2 = Vector2.Distance(transform.position, building.transform.position);
  50.                 if (distance1 > distance2)
  51.                     _target = building.transform.position;
  52.             }
  53.         }
  54.     }
  55.  
  56.     private void OnCollisionEnter2D(Collision2D collision)
  57.     {
  58.         if (collision.gameObject.TryGetComponent(out Building building))
  59.         {
  60.             building.Health.Damage(_damage);
  61.             Destroy(gameObject);
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement