Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(Rigidbody2D))]
- [RequireComponent(typeof(Health))]
- public class Enemy : MonoBehaviour
- {
- public static Enemy Create(Vector2 position)
- {
- var enemyPrefab = Resources.Load<Enemy>(nameof(Enemy));
- return Instantiate(enemyPrefab, position, Quaternion.identity);
- }
- [Header("Parameters")]
- [SerializeField] private float _speed;
- [SerializeField] private int _damage;
- [SerializeField] private float _targetMaxRadius;
- [SerializeField] private float _findTargetsCooldown;
- public Health Health { get; private set; }
- private Rigidbody2D _rigidbody;
- private Vector2 _target;
- private void Start()
- {
- Health = GetComponent<Health>();
- Health.OnDeadEvent += OnDead;
- _rigidbody = GetComponent<Rigidbody2D>();
- InvokeRepeating(nameof(LookForTargets), 0, _findTargetsCooldown);
- }
- private void OnDead() => Destroy(gameObject);
- private void FixedUpdate()
- {
- var direction = (_target - (Vector2)transform.position).normalized;
- _rigidbody.velocity = direction * _speed;
- }
- private void LookForTargets()
- {
- _target = Vector2.zero;
- var colliders = Physics2D.OverlapCircleAll(transform.position, _targetMaxRadius);
- foreach (var collider in colliders)
- {
- if (collider.TryGetComponent(out Building building))
- {
- var distance1 = Vector2.Distance(transform.position, _target);
- var distance2 = Vector2.Distance(transform.position, building.transform.position);
- if (distance1 > distance2)
- _target = building.transform.position;
- }
- }
- }
- private void OnCollisionEnter2D(Collision2D collision)
- {
- if (collision.gameObject.TryGetComponent(out Building building))
- {
- building.Health.Damage(_damage);
- Destroy(gameObject);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement