Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
0
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public Transform player;
    public GameObject attackObject;
    public float attackDistance = 3f;
    public float attackHeight = 4f;
    public float attackDuration = 1f;
    public float attackSpeed = 5f;
    public int attackCount = 3;

    private bool isAttacking = false;
    private int currentAttackCount = 0;

    void Update()
    {
        if (!isAttacking && Vector3.Distance(transform.position, player.position) < attackDistance)
        {
            StartCoroutine(Attack());
        }
    }

    IEnumerator Attack()
    {
        isAttacking = true;

        while (currentAttackCount < attackCount)
        {
            // Move up to the attack height
            float t = 0f;
            Vector3 startPos = transform.position;
            Vector3 endPos = new Vector3(transform.position.x, transform.position.y + attackHeight, transform.position.z);
            while (t < 1f)
            {
                t += Time.deltaTime / attackDuration;
                transform.position = Vector3.Lerp(startPos, endPos, t);
                yield return null;
            }

            // Instantiate the attack object
            Instantiate(attackObject, player.position, Quaternion.identity);

            // Move to the player
            t = 0f;
            startPos = transform.position;
            endPos = player.position;
            while (t < 1f)
            {
                t += Time.deltaTime * attackSpeed / Vector3.Distance(startPos, endPos);
                transform.position = Vector3.Lerp(startPos, endPos, t);
                yield return null;
            }

            // Check if we reached the player
            if (Vector3.Distance(transform.position, player.position) < 0.1f)
            {
                currentAttackCount++;
                if (currentAttackCount >= attackCount)
                {
                    Destroy(gameObject);
                    yield break;
                }
            }
        }

        isAttacking = false;
    }
}