본문 바로가기
개발/C#

유니티 C# 자동 전투 적 인공지능 간단 구현하기

by SPNK 2024. 2. 29.
반응형

코드 작성

using UnityEngine;

public class AutoAttack : MonoBehaviour
{
    public Transform warrior;
    public Transform monster;
    public float moveSpeed = 5f;
    public float attackRange = 1.5f;

    private bool isAttacking = false;

    void Update()
    {
        // 용사와 몬스터 사이의 거리 계산
        float distance = Vector2.Distance(warrior.position, monster.position);

        // 거리가 공격 범위 이내이면 공격
        if (distance <= attackRange)
        {
            Attack();
        }
        else
        {
            // 거리가 공격 범위보다 크면 이동
            Move();
        }
    }

    void Move()
    {
        // 몬스터를 향해 이동
        Vector2 direction = (monster.position - warrior.position).normalized;
        warrior.Translate(direction * moveSpeed * Time.deltaTime);
    }

    void Attack()
    {
        if (!isAttacking)
        {
            // 공격 애니메이션 또는 기타 공격 처리
            Debug.Log("용사가 몬스터를 공격합니다!");

            // 몬스터의 체력을 감소시키고, 필요에 따라 몬스터의 사망 여부를 체크할 수 있습니다.
            MonsterHealth monsterHealth = monster.GetComponent<MonsterHealth>();
            if (monsterHealth != null)
            {
                monsterHealth.TakeDamage(10); // 10은 임의의 데미지 값입니다.
            }

            // 일정 시간 동안 공격을 막기 위한 쿨다운
            isAttacking = true;
            Invoke("ResetAttack", 1f); // 1초 후에 다시 공격 가능하도록 설정
        }
    }

    void ResetAttack()
    {
        isAttacking = false;
    }
}
반응형

댓글