【Unity】ステートマシンを使った敵AIのコードの書き方!

ステートマシンを使用して、複数の状態を持つ敵AIを実装するスクリプトです。これを使うと、敵が異なる状態(パトロール、追跡、攻撃)を持つようになります。

using UnityEngine;

public enum EnemyState
{
    Patrol,
    Chase,
    Attack
}

public class EnemyStateMachine : MonoBehaviour
{
    public EnemyState currentState;
    public Transform player;
    public float chaseDistance = 5f;
    public float attackDistance = 1.5f;
    public float speed = 2f;
    private Transform[] patrolPoints;
    private int currentPatrolIndex;

    void Start()
    {
        patrolPoints = new Transform[transform.childCount];
        for (int i = 0; i < patrolPoints.Length; i++)
        {
            patrolPoints[i] = transform.GetChild(i);
        }
        currentState = EnemyState.Patrol;
    }

    void Update()
    {
        switch (currentState)
        {
            case EnemyState.Patrol:
                Patrol();
                break;
            case EnemyState.Chase:
                Chase();
                break;
            case EnemyState.Attack:
                Attack();
                break;
        }
    }

    void Patrol()
    {
        Transform target = patrolPoints[currentPatrolIndex];
        transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);

        if (Vector3.Distance(transform.position, target.position) < 0.2f)
        {
            currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length;
        }

        if (Vector3.Distance(transform.position, player.position) < chaseDistance)
        {
            currentState = EnemyState.Chase;
        }
    }

    void Chase()
    {
        transform.position = Vector3.MoveTowards(transform.position, player.position, speed * Time.deltaTime);

        if (Vector3.Distance(transform.position, player.position) < attackDistance)
        {
            currentState = EnemyState.Attack;
        }
        else if (Vector3.Distance(transform.position, player.position) > chaseDistance)
        {
            currentState = EnemyState.Patrol;
        }
    }

    void Attack()
    {
        Debug.Log("Attack the player!");
        if (Vector3.Distance(transform.position, player.position) > attackDistance)
        {
            currentState = EnemyState.Chase;
        }
    }
}

コメント

タイトルとURLをコピーしました