private void Awake()
    {
        Player player = FindObjectOfType <Player>();

        _navMeshAgent = GetComponent <NavMeshAgent>();
        _entity       = GetComponent <Entity>();
        _stateMachine = new StateMachine();

        // Just want to explain this line further b/c there's a lot going on here.
        // I believe what this is doing is registering a lambda function with StateMachine.OnStateChanged.
        // This lamdba function receives "state", and simply called EntityStateMachine.OnStateChanged(state).
        _stateMachine.OnStateChanged += state => OnEntityStateChanged?.Invoke(state);

        Idle        idle        = new Idle();
        ChasePlayer chasePlayer = new ChasePlayer(_navMeshAgent, player);
        Attack      attack      = new Attack();
        Dead        dead        = new Dead(_entity);

        // Idle -> Chase
        _stateMachine.AddTransition(
            idle,
            chasePlayer,
            () => DistanceFlat(_navMeshAgent.transform.position, player.transform.position) < 5f
            );

        // Chase -> Attack
        _stateMachine.AddTransition(
            chasePlayer,
            attack,
            () => DistanceFlat(_navMeshAgent.transform.position, player.transform.position) <= 2f
            );

        /*
         * // Attack -> Chase
         * _stateMachine.AddTransition(
         *  attack,
         *  chasePlayer,
         *  () => DistanceFlat(_navMeshAgent.transform.position, player.transform.position) > 2f
         * );
         */

        // Any -> Dead
        _stateMachine.AddAnyTransition(dead, () => _entity.Health <= 0);

        _stateMachine.SetState(idle);
    }
示例#2
0
        private void Awake()
        {
            var player = FindObjectOfType <Player>();

            _entity       = GetComponent <Entity.Entity>();
            _navMeshAgent = GetComponent <NavMeshAgent>();
            _stateMachine = new StateMachine();
            _stateMachine.OnStateChanged += state => OnEntityStateChanged?.Invoke(state);

            var idle        = new Idle();
            var chasePlayer = new ChasePlayer(_navMeshAgent, player);
            var attack      = new Attack();
            var dead        = new Dead(_entity);

            _stateMachine.AddTransition(idle, chasePlayer, () => Vector3.Distance(_navMeshAgent.transform.position, player.transform.position) > 2f);
            _stateMachine.AddTransition(chasePlayer, attack, () => Vector3.Distance(_navMeshAgent.transform.position, player.transform.position) < 2f);
            _stateMachine.AddTransition(attack, chasePlayer, () => Vector3.Distance(_navMeshAgent.transform.position, player.transform.position) > 2f);
            _stateMachine.AddAnyTransition(dead, () => _entity.Health <= 0);

            _stateMachine.SetState(idle);
        }