using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
public int attackDamage = 10; // Damage dealt by the enemy
public Transform attackPoint; // The point from which the attack originates
public float attackRange = 1f; // Range of the attack
public LayerMask playerLayer; // Layer to detect the player
public float attackCooldown = 2f; // Time between attacks
Animator animator;
private Enemy enemy; // Reference to the enemy's state
private bool canAttack = true; // Cooldown flag for attacks
private void Awake()
{
animator = GetComponent<Animator>();
// Reference to the Enemy script on the same GameObject
enemy = GetComponent<Enemy>();
}
public void PerformAttack()
{
// Ensure the enemy is alive and can attack
if (!enemy.isAlive || !canAttack) return;
// Check for player within attack range
Collider2D playerCollider = Physics2D.OverlapCircle(attackPoint.position, attackRange, playerLayer);
if (playerCollider != null)
{
// Damage the player if detected
HealthSystem playerHealth = playerCollider.GetComponent<HealthSystem>();
if (playerHealth != null)
{
playerHealth.TakeDamage(attackDamage);
Debug.Log("Enemy hit the player: " + playerCollider.name);
}
}
// Trigger attack animation
if (animator != null)
{
animator.SetTrigger("attack");
}
// Start cooldown
StartCoroutine(AttackCooldown());
}
private IEnumerator AttackCooldown()
{
canAttack = false; // Prevent further attacks
yield return new WaitForSeconds(attackCooldown); // Wait for cooldown duration
canAttack = true; // Allow attacking again
}
// Debugging: Visualize the attack range in the editor
private void OnDrawGizmosSelected()
{
if (attackPoint == null) return;
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}