using UnityEngine; public class Enemy : MonoBehaviour { public int maxHealth = 2; //Set max health of the enemy private int currentHealth; public float moveSpeed = 2f; public Transform pointA; //Set a point for the enemy to move between (pointA to pointB) public Transform pointB; private Vector3 target; private float attackCooldown = 1f; // Seconds between attacks private float lastAttackTime; void Start() { currentHealth = maxHealth; target = pointB.position; //Automatically start heading towards point B EnemyManager.RegisterEnemy(); } void Update() { Patrol(); //Constanstly move between patrol positions } private void OnDestroy() { EnemyManager.EnemyDied(); } void Patrol() //Patrol logic { transform.position = Vector2.MoveTowards(transform.position, target, moveSpeed * Time.deltaTime); //Movement logic // Flip enemy sprite to face the direction it's moving Vector3 direction = target - transform.position; if (direction.x > 0) { transform.localScale = new Vector3(1, 1, 1); // Face right } else if (direction.x < 0) { transform.localScale = new Vector3(-1, 1, 1); // Face left } //Change direction when at the other point if (Vector2.Distance(transform.position, pointA.position) < 0.1f) { target = pointB.position; } else if (Vector2.Distance(transform.position, pointB.position) < 0.1f) { target = pointA.position; } } public void TakeDamage(int damage) { currentHealth -= damage; if (currentHealth <= 0) { Die(); } } void Die() { Destroy(gameObject); } // Damage player on contact, with cooldown to avoid spamming damage every frame private void OnTriggerStay2D(Collider2D collision) { if (collision.CompareTag("Player") && Time.time >= lastAttackTime + attackCooldown) { PlayerHealth playerHealth = collision.GetComponent(); if (playerHealth != null) { playerHealth.TakeDamage(1); lastAttackTime = Time.time; } } } }