private void Start()
    {
        //IA2-P2
        SetTeamData();

        rb            = this.gameObject.GetComponent <Rigidbody>();
        _initialSpeed = 10;
        _navMeshAgent = GetComponent <NavMeshAgent>();
        initPos       = transform.position;
        sm            = new StateMachine();

        //Creo los estados
        var idle               = new Idle_State(this);
        var move               = new Move_State(this);
        var stunned            = new Stunned_State(this);
        var searchFlag         = new SearchForFlag_State(this);
        var chaseFlag          = new ChaseFlag_State(this);
        var carryFlag          = new CarryFlagToBase_State(this);
        var protectFlagCarrier = new ProtectFlagCarrier_State(this);

        //Los registro para hacer cambios forzados de estados
        statesRegistry.Add(Enums.SM_STATES.Idle, idle);
        statesRegistry.Add(Enums.SM_STATES.Move, move);
        statesRegistry.Add(Enums.SM_STATES.Stunned, stunned);
        statesRegistry.Add(Enums.SM_STATES.SearchFlag, searchFlag);
        statesRegistry.Add(Enums.SM_STATES.ChaseFlag, chaseFlag);
        statesRegistry.Add(Enums.SM_STATES.CarryFlagToBase, carryFlag);
        statesRegistry.Add(Enums.SM_STATES.ProtectFlagCarrier, protectFlagCarrier);

        //Agrego transiciones
        At(searchFlag, move, ImStillSearching());
        At(move, searchFlag, FinishMomevent());
        At(chaseFlag, carryFlag, HasFlag());
        At(carryFlag, searchFlag, ImStillSearching());
        At(stunned, searchFlag, ImStillSearching());
        At(protectFlagCarrier, searchFlag, ImStillSearching());

        //Shortcut para agregar transiciones
        void At(IState from, IState to, Func <bool> condition) => sm.AddTransition(from, to, condition);

        //Condiciones
        Func <bool> IsStunned() => () => isStunned;
        Func <bool> ImStillSearching() => () => knowsWhereFlagIs == false && hasFlag == false && isStunned == false;
        Func <bool> FinishMomevent() => () => GetComponent <NavMeshAgent>().velocity == Vector3.zero;
        Func <bool> FindFlag() => () => knowsWhereFlagIs && hasFlag == false && isStunned == false && sm.CurrentState != protectFlagCarrier;
        Func <bool> HasFlag() => () => hasFlag;

        //Desde cualquier estado
        sm.AddAnyTransition(stunned, IsStunned());
        sm.AddAnyTransition(chaseFlag, FindFlag());

        //Arranco la maquina en un estado
        sm.SetState(searchFlag);
    }
Example #2
0
    private void Awake()
    {
        stateMachine = new StateMachine();

        //initialize states
        var idle           = new IdleGameObjectState();
        var rotating       = new ActivateRotateWithinRadius(gameObject, rotationAngle, rotationAxis);
        var toggleAppear   = new ToggleAppearWithinRadius(gameObject, toggleTimeInSecs);
        var destroyOnInput = new DestroyOnInput(gameObject, destroyDelayInSecs, destroySoundEffect, destroySoundEffectVolume);

        //add transitions
        stateMachine.AddTransition(idle, rotating, IsInsideRotationRadius());
        stateMachine.AddTransition(rotating, idle, IsOutsideRotationRadius());
        stateMachine.AddTransition(rotating, toggleAppear, IsInsideToggleRadius());
        stateMachine.AddTransition(toggleAppear, rotating, IsOutsideToggleRadius());
        stateMachine.AddAnyTransition(destroyOnInput, WasDestroyAllPressed());

        //define transitions predicates
        Func <bool> IsInsideRotationRadius() => () =>
        {
            return(Vector3.Distance(activationTargetObject.transform.position, gameObject.transform.position) <= rotationActivationRadius.Value &&
                   Vector3.Distance(activationTargetObject.transform.position, gameObject.transform.position) > toggleActivationRadius.Value);
        };

        Func <bool> IsOutsideRotationRadius() => () => Vector3.Distance(activationTargetObject.transform.position, gameObject.transform.position) > rotationActivationRadius.Value;
        Func <bool> IsInsideToggleRadius() => () => Vector3.Distance(activationTargetObject.transform.position, gameObject.transform.position) <= toggleActivationRadius.Value;
        Func <bool> IsOutsideToggleRadius() => () => Vector3.Distance(activationTargetObject.transform.position, gameObject.transform.position) > toggleActivationRadius.Value;
        Func <bool> WasDestroyAllPressed() => () => Input.GetKeyDown(destroyKeyCode.Value);

        //set initial state
        stateMachine.SetState(idle);
    }
Example #3
0
    private void Awake()
    {
        var navMeshAgent = GetComponent <NavMeshAgent>();

        _stateMachine = new StateMachine();

        inputReader = GetComponent <InputReader>();
        rb          = GetComponent <Rigidbody>();

        var idle    = new Idle(this, slowRate);
        var move    = new Move(this, inputReader, speed);
        var jump    = new Jump(this, jumpSpeed);
        var fall    = new Fall();
        var runAway = new RunAway(this, runAwayDestination);

        At(idle, move, () => HasMoveInput());
        At(move, idle, () => !HasMoveInput());
        At(idle, jump, () => HasJumpInput() && isGrounded);
        At(move, jump, () => HasJumpInput() && isGrounded);
        At(jump, fall, () => isFalling());
        At(fall, idle, () => isGrounded);
        At(runAway, idle, () => !isRunningAway);

        _stateMachine.AddAnyTransition(runAway, () => isRunningAway);

        _stateMachine.SetState(fall);

        void At(IState from, IState to, Func <bool> condition) => _stateMachine.AddTransition(from, to, condition);
    }
Example #4
0
        private void InitStateMachine()
        {
            StateMachine = new StateMachine();

            void AddTransition(IState from, IState to, Func <bool> condition) =>
            StateMachine.AddTransition(from, to, condition);

            void AddAnyTransition(IState state, Func <bool> condition) =>
            StateMachine.AddAnyTransition(state, condition);

            Func <bool> ReachedMovePoint() => () => PointToMove == null;
            Func <bool> HasPointToMove() => () => PointToMove != null;
            Func <bool> IsTimeOutFinished() => () => timer.finished;
            Func <bool> IsStopped() => () => CurrentVerticalMove == MinAxisMove;
            Func <bool> HasTarget() => () => currentTarget != null;
            Func <bool> HasNoTarget() => () => currentTarget == null;

            Idle idle = new Idle(this, Animator);
            SearchPointToMove searchPointToMove = new SearchPointToMove(this);
            MoveToPoint       moveToPoint       = new MoveToPoint(this, Animator);
            TimeOut           timeOut           = new TimeOut(this, timer);
            Attack            attack            = new Attack(this);

            AddTransition(idle, timeOut, IsStopped());
            AddTransition(timeOut, searchPointToMove, IsTimeOutFinished());
            AddTransition(searchPointToMove, moveToPoint, HasPointToMove());
            AddTransition(moveToPoint, idle, ReachedMovePoint());
            AddTransition(attack, idle, HasNoTarget());

            AddAnyTransition(attack, HasTarget());

            StateMachine.SetEntryPoint(idle);
        }
Example #5
0
        protected override void SetUpStates()
        {
            var idleState           = new IdleState(this);
            var largeAttackState    = new AttackState(enemyWeapon, Animator, Mover, Player);
            var prepareShortAttack  = new PlayAnimationState(Animator, Player, Mover, "prepareShortAttack", 0.5f);
            var shortRangeState     = new AttackState(shortRangeWeapon, transform, Mover, Player);
            var idleShortRangeState = new IdleState(this);
            var dieAnimation        = new PlayAnimationState(Animator, Player, Mover, "die", 0.67f);
            var destroySelf         = new DestroySelfState(gameObject);

            StateMachine.AddTransition(idleState, largeAttackState, PlayerInsideRange);
            StateMachine.AddTransition(largeAttackState, idleState, () => !PlayerInsideRange());
            StateMachine.AddTransition(largeAttackState, prepareShortAttack, HealthBelowThreshold);
            StateMachine.AddTransition(prepareShortAttack, idleShortRangeState, FinishPlayingAnimation(prepareShortAttack));
            StateMachine.AddTransition(idleShortRangeState, shortRangeState, PlayerInsideRange);
            StateMachine.AddTransition(shortRangeState, idleShortRangeState, () => !PlayerInsideRange());

            StateMachine.AddAnyTransition(dieAnimation, EnemyDie);
            StateMachine.AddTransition(dieAnimation, destroySelf, FinishPlayingAnimation(dieAnimation));

            StateMachine.SetState(idleState);

            _initialHealth = Stats.Health;
            bool HealthBelowThreshold() => Stats.Health <= _initialHealth *laserHealthPercentage;
        }
Example #6
0
    void InitStateMachine()
    {
        _stateMachine = new StateMachine();

        var menu         = new StartMenuState(_startMenu, _gameUI, this);
        var p1           = new PlayerMoveState(_player1);
        var p2           = new PlayerMoveState(_player2);
        var checkEndGame = new CheckEndGameState(_checkEndGameProcessor);
        var endGame      = new EndGameState(_endGameMenu, _gameUI, _checkEndGameProcessor, _grid, _player1, _player2);

        _stateMachine.AddTransition(menu, p1, TimeToPlay());
        _stateMachine.AddTransition(p1, p2, SwitchToPlayer2());
        _stateMachine.AddTransition(p2, checkEndGame, SwitchToCheckEnd());
        _stateMachine.AddTransition(checkEndGame, p1, SwitchToPlayer1());
        _stateMachine.AddTransition(checkEndGame, endGame, EndGame());
        _stateMachine.AddTransition(endGame, p1, Restart());
        _stateMachine.AddTransition(endGame, menu, ToStartMenu());

        _stateMachine.AddAnyTransition(menu, ExitGame());

        _stateMachine.SetState(menu);
        //условия перехода
        Func <bool> TimeToPlay() => () => _startMenu._startGame;//начинаем игру из стартового меню
        Func <bool> SwitchToPlayer2() => () => _player1._endMove;
        Func <bool> SwitchToCheckEnd() => () => _player2._endMove;
        Func <bool> SwitchToPlayer1() => () => _checkEndGameProcessor.ContinueGame();
        Func <bool> EndGame() => () => !_checkEndGameProcessor.ContinueGame();; //ничья или ктото победил
        Func <bool> Restart() => () => _endGameMenu._restartGame;               //рестарт игры из экрана конца игры
        Func <bool> ToStartMenu() => () => _endGameMenu._mainMenu;              //переходим в стартовое меню из экрана конца игры
        Func <bool> ExitGame() => () => false;                                  //выход в стартовое меню из любого состояния
    }
Example #7
0
    // Start is called before the first frame update
    void Start()
    {
        #region Configuring State Machine

        _animator       = GetComponent <Animator>();
        _spriteRenderer = GetComponent <SpriteRenderer>();
        _rb             = GetComponent <Rigidbody2D>();
        _stateMachine   = new StateMachine();

        var randomMoving       = new RandomMoving(this, _animator, _rb);
        var enemyIdle          = new EnemyIdle(this, _animator, _rb);
        var enemyDashAttacking = new EnemyDashAttacking(this, _animator, _rb);

        // Assigning transitions
        At(randomMoving, enemyIdle, IsIdle());
        At(enemyIdle, randomMoving, IsMoving());

        _stateMachine.AddAnyTransition(enemyDashAttacking, IsInRangeAndAttackReady());
        At(enemyDashAttacking, enemyIdle, IsNotAttacking());

        // Starting state
        _stateMachine.SetState(enemyIdle);

        // Method to assign transitions easily
        void At(IState to, IState from, Func <bool> condition) => _stateMachine.AddTransition(to, from, condition);

        #endregion

        health = MaxHealth;
    }
    private void Awake()
    {
        var targetSelection = new TurretTargetSelector(this, range);
        var turretShoot     = new TurretShoot(this, shotFrequency);
        var beingCarried    = new BeingCarried(this);

        stateMachine = new StateMachine();

        stateMachine.AddTransition(targetSelection, turretShoot, HasTarget());
        stateMachine.AddAnyTransition(targetSelection, IsReadyForTarget());
        stateMachine.AddAnyTransition(beingCarried, IsBeingCarried());

        stateMachine.SetState(targetSelection);

        Func <bool> HasTarget() => () => Target != null && Target.gameObject.activeInHierarchy;
        Func <bool> IsReadyForTarget() => () => (Target == null || !Target.gameObject.activeInHierarchy) && carryingObject == null;;
        Func <bool> IsBeingCarried() => () => carryingObject != null;;
    }
Example #9
0
    private void Start()
    {
        #region Configuring State Machine

        _animator       = GetComponent <Animator>();
        _spriteRenderer = GetComponent <SpriteRenderer>();
        _rb             = GetComponent <Rigidbody2D>();
        _collider       = GetComponent <Collider2D>();

        _stateMachine = new StateMachine();

        // Instantiating states
        var moving       = new Moving(this, _animator);
        var idle         = new Idle(this, _animator);
        var dashing      = new Dashing(this, _animator, _rb, _collider);
        var attacking    = new Attacking(this, _animator, _rb);
        var boomeranging = new Boomeranging(this, _animator, _rb);
        var swapping     = new Swapping(this, _animator, _rb);

        // Assigning transitions
        At(moving, idle, IsIdle());
        At(idle, moving, IsMoving());

        // Dashing
        At(idle, dashing, IsDashing());
        At(moving, dashing, IsDashing());
        At(dashing, idle, IsNotDashing());

        // Attacking
        At(idle, attacking, IsAttacking());
        At(moving, attacking, IsAttacking());
        At(attacking, idle, IsNotAttacking());

        // Boomeranging
        At(idle, boomeranging, IsBoomeranging());
        At(moving, boomeranging, IsBoomeranging());
        At(boomeranging, idle, IsNotBoomeranging());

        // Swapping
        _stateMachine.AddAnyTransition(swapping, IsSwapping());
        At(swapping, idle, IsNotSwapping());

        // Starting state
        _stateMachine.SetState(moving);

        // Method to assign transitions easily
        void At(IState to, IState from, Func <bool> condition) => _stateMachine.AddTransition(to, from, condition);

        #endregion

        #region Instantiating instance variables
        // Base sorting layer
        baseLayer = GetComponent <SpriteRenderer>().sortingOrder;
        #endregion
    }
Example #10
0
    private void Start()
    {
        #region Configuring State Machine

        _animator       = GetComponent <Animator>();
        _spriteRenderer = GetComponent <SpriteRenderer>();
        _rb             = GetComponent <Rigidbody2D>();

        _stateMachine = new StateMachine();

        // Instantiating states
        var running = new Running(this, _animator);
        var idle    = new Idle(this, _animator);
        var dashing = new Dashing(this, _animator, _rb);
        var stunned = new Stunned(this, _rb);

        // Assigning transitions
        _stateMachine.AddAnyTransition(stunned, IsStunned());
        At(running, idle, IsIdle());
        At(idle, running, IsMoving());
        At(idle, dashing, IsDashing());
        At(running, dashing, IsDashing());
        At(stunned, idle, IsNotStunned());

        // Starting state
        _stateMachine.SetState(running);

        // Method to assign transitions easily
        void At(IState to, IState from, Func <bool> condition) => _stateMachine.AddTransition(to, from, condition);

        // Transition conditions
        Func <bool> IsMoving() => () => (xInput != 0 || yInput != 0);
        Func <bool> IsIdle() => () => (xInput == 0 && yInput == 0);
        Func <bool> IsDashing() => () => (isDashing);
        Func <bool> IsNotDashing() => () => (!isDashing);
        Func <bool> IsStunned() => () => (isStunned);
        Func <bool> IsNotStunned() => () => (!isStunned);

        #endregion

        #region Instantiating instance variables
        // Get boundaries object to set player movement boundaries
        GameObject boundaryObj = GameObject.Find("Boundaries");
        Boundaries boundary    = boundaryObj.GetComponent <Boundaries>();
        xBoundary = boundary.playerBoundary_x;
        yBoundary = boundary.playerBoundary_y;

        // Base sorting layer
        baseLayer = GetComponent <SpriteRenderer>().sortingOrder;
        #endregion
    }
Example #11
0
        public void transition_from_any_state_to_new_state_when_condition_is_met()
        {
            var stateMachine = new StateMachine();

            IState firstState  = Substitute.For <IState>();
            IState secondState = Substitute.For <IState>();

            bool ShouldTransitionToNewState() => true;

            stateMachine.AddAnyTransition(secondState, () => ShouldTransitionToNewState());

            stateMachine.SetState(firstState);
            Assert.AreSame(firstState, stateMachine.CurrentState);
            stateMachine.Tick();

            Assert.AreSame(secondState, stateMachine.CurrentState);
        }
        public void Transition_From_Any_Switches_State_When_Condition_Met()
        {
            StateMachine stateMachine = new StateMachine();

            IState firstState  = Substitute.For <IState>();
            IState secondState = Substitute.For <IState>();

            bool ShouldTransitionState() => true;

            stateMachine.AddAnyTransition(secondState, ShouldTransitionState);

            stateMachine.SetState(firstState);
            Assert.AreSame(firstState, stateMachine.CurrentState);

            stateMachine.Tick();
            Assert.AreSame(secondState, stateMachine.CurrentState);
        }
    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);
    }
    private void Awake()
    {
        //For scared condition
        orangeDino = GameObject.FindObjectOfType <OrangeDinoBoo>();

        //For angry condition
        greenDino = GameObject.FindObjectOfType <CubeDinoCollect>();

        //For sad condition
        calCounter = GameObject.FindObjectOfType <CubeCaloryCounter>();

        //friend bot not written yet


        _stateMachine = new StateMachine();


        //here the Emotion States are declared and instantiated:
        var scared = new Scared(this /*,  animator*/);
        var happy  = new Happy(this);
        var sad    = new Sad(this);
        var angry  = new Angry(this);

        //var depressed = new Depressed(this);

        //here ALL the transitions are added(declared) to _transition
        At(happy, sad, calCounter.calories > hungerCal);
        At(sad, happy, calCounter.calories < hungerCal);



        At(angry, happy, orangeDino.booNear1);
        At(happy, angry, angry.timeStuck > 1f);

        _stateMachine.AddAnyTransition(scared, orangeDino.booNear1);
        At(happy, scared, scared.timeStuck > 3f);



        //Set the starting ( happy) state
        _stateMachine.SetState(happy);


        void At(IState to, IState from, bool condition) => _stateMachine.AddTransition(to, from, condition);
    }
Example #15
0
        private void Awake()
        {
            var navMeshAgent       = GetComponent <NavMeshAgent>();
            var animator           = GetComponent <Animator>();
            var enemyDetector      = gameObject.AddComponent <EnemyDetector>();
            var fleeParticleSystem = gameObject.GetComponentInChildren <ParticleSystem>();

            _stateMachine = new StateMachine();

            var search                    = new SearchForResource(this);
            var moveToSelected            = new MoveToSelectedResource(this, navMeshAgent, animator);
            var harvest                   = new HarvestResource(this, animator);
            var returnToStockpile         = new ReturnToStockpile(this, navMeshAgent, animator);
            var placeResourcesInStockpile = new PlaceResourcesInStockpile(this);
            var flee = new Flee(this, navMeshAgent, enemyDetector, animator, fleeParticleSystem);

            At(search, moveToSelected, HasTarget());
            At(moveToSelected, search, StuckForOverASecond());
            At(moveToSelected, harvest, ReachedResource());
            At(harvest, search, TargetIsDepletedAndICanCarryMore());
            At(harvest, returnToStockpile, InventoryFull());
            At(returnToStockpile, placeResourcesInStockpile, ReachedStockpile());
            At(placeResourcesInStockpile, search, () => _gathered == 0);

            _stateMachine.AddAnyTransition(flee, () => enemyDetector.EnemyInRange);
            At(flee, search, () => enemyDetector.EnemyInRange == false);

            _stateMachine.SetState(search);

            void At(IState to, IState from, Func <bool> condition) => _stateMachine.AddTransition(to, from, condition);
            Func <bool> HasTarget() => () => Target != null;
            Func <bool> StuckForOverASecond() => () => moveToSelected.TimeStuck > 1f;

            Func <bool> ReachedResource() => () => Target != null &&
            Vector3.Distance(transform.position, Target.transform.position) < 1f;

            Func <bool> TargetIsDepletedAndICanCarryMore() =>
            () => (Target == null || Target.IsDepleted) && !InventoryFull().Invoke();

            Func <bool> InventoryFull() => () => _gathered >= _maxCarried;

            Func <bool> ReachedStockpile() => () => StockPile != null &&
            Vector3.Distance(transform.position, StockPile.transform.position) <
            1f;
        }
Example #16
0
        private void Awake()
        {
            _stateMachine = new StateMachine();

            var search   = new Empty();
            var approach = new Approach(this, _tagHerbFood);
            var flee     = new Flee(this, _tagCarnivore);

            _stateMachine.AddAnyTransition(flee, () => vision.TargetInRange(_tagCarnivore));
            At(flee, search, () => !vision.TargetInRange(_tagCarnivore));
            At(search, approach, () => vision.TargetInRange(_tagHerbFood));
            //At(approach, search, () => !vision.TargetInRange(_tagHerbFood, viewDistance));

            _stateMachine.SetState(search);

            void At(IState from, IState to, Func <bool> condition) =>
            _stateMachine.AddTransition(from, to, condition);
        }
Example #17
0
    //public Func<bool> IsAttacking() => () => (isAttacking);
    #endregion

    // Start is called before the first frame update
    void Start()
    {
        #region Configuring State Machine

        _animator       = GetComponent <Animator>();
        _spriteRenderer = GetComponent <SpriteRenderer>();
        _rb             = GetComponent <Rigidbody2D>();
        _collider       = GetComponent <Collider2D>();
        _stateMachine   = new StateMachine();

        var sheepCentralState            = new SheepCentralState(this);
        var sheepMoving                  = new SheepMoving(this, _animator, _rb);
        var sheepProjectiling            = new SheepProjectiling(this, _animator, _rb);
        var sheepDashing                 = new SheepDashAttacking(this, _animator, _rb);
        var sheepLaunchingExplodingSheep = new SheepLaunchingExplodingSheep(this, _animator, _rb);
        var sheepPhaseChangeState        = new SheepPhaseChangeState(this, _animator, _spriteRenderer);

        //// Assigning transitions
        At(sheepCentralState, sheepProjectiling, IsProjectiling());
        At(sheepCentralState, sheepMoving, IsMoving());
        At(sheepCentralState, sheepDashing, IsDashing());
        At(sheepCentralState, sheepLaunchingExplodingSheep, IsLaunchingExplodingSheep());

        At(sheepProjectiling, sheepCentralState, IsNotProjectiling());
        At(sheepMoving, sheepCentralState, IsNotMoving());
        At(sheepDashing, sheepCentralState, IsNotDashing());
        At(sheepLaunchingExplodingSheep, sheepCentralState, IsNotLaunchingExplodingSheep());

        // Can go into phase change state from any state. Only triggers once.
        _stateMachine.AddAnyTransition(sheepPhaseChangeState, IsPhaseChanging());
        At(sheepPhaseChangeState, sheepLaunchingExplodingSheep, IsLaunchingExplodingSheep());

        //// Starting state
        _stateMachine.SetState(sheepMoving);

        // Method to assign transitions easily
        void At(IState from, IState to, Func <bool> condition) => _stateMachine.AddTransition(from, to, condition);

        #endregion

        health = MaxHealth;
    }
Example #18
0
    public override void Place()
    {
        base.Place();

        LevelController = FindObjectOfType <LevelController>();

        _stateMachine = new StateMachine();

        _walkState = new WalkState(this);
        var fallState  = new FallState(this);
        var climbState = new ClimbState(this);
        var dieState   = new DieState(this);

        _stateMachine.AddTransition(_walkState, fallState, () => !OnGround);
        _stateMachine.AddTransition(fallState, _walkState, () => OnGround);
        _stateMachine.AddTransition(_walkState, climbState, () => Climbing);
        _stateMachine.AddTransition(climbState, _walkState, () => !Climbing);

        _stateMachine.AddAnyTransition(dieState, () => _dead);
    }
Example #19
0
        protected override void SetUpStates()
        {
            var idleState           = new IdleState(leftPosition, rightPosition, this, Mover);
            var startAttackingState =
                new PlayAnimationState(Animator, Player, Mover, "startAttacking", prepareToAttackAnimationLength);
            var attackState        = new AttackState(enemyWeapon, Animator, Mover, Player);
            var stopAttackingState =
                new PlayAnimationState(Animator, Player, Mover, "stopAttacking", prepareToAttackAnimationLength);
            var dieState    = new PlayAnimationState(Animator, Player, Mover, "die", dieAnimationLength);
            var destroySelf = new DestroySelfState(gameObject);

            StateMachine.AddTransition(idleState, startAttackingState, PlayerInsideRange);
            StateMachine.AddTransition(startAttackingState, attackState, FinishPlayingAnimation(startAttackingState));
            StateMachine.AddTransition(attackState, stopAttackingState, PlayerOutsideRange);
            StateMachine.AddTransition(stopAttackingState, idleState, FinishPlayingAnimation(stopAttackingState));
            StateMachine.AddTransition(dieState, destroySelf, FinishPlayingAnimation(dieState));

            StateMachine.AddAnyTransition(dieState, EnemyDie);

            StateMachine.SetState(idleState);

            bool PlayerOutsideRange() => !PlayerInsideRange();
        }
Example #20
0
 protected void AddAnyTransition(IState state, Func <bool> condition) => StateMachine.AddAnyTransition(state, condition);
Example #21
0
    private void Awake()
    {
        //Get all necessary components
        Target = GameObject.Find("Jugador");
        if (Target == null)
        {
            Debug.LogError("Target not found!");
            return;
        }
        navMeshAgent = GetComponent <NavMeshAgent>();
        if (navMeshAgent == null)
        {
            Debug.LogError("NavMesh Agent component missing!");
            return;
        }
        navMeshAgent.speed = enemy.enemyData.Speed;

        RangedAttackProbability = enemy.RangedAttackProbability;

        switch (enemy.AttackPreference)
        {
        case AttackTypes.Melee:
            AttackPreference = "melee";
            break;

        case AttackTypes.Ranged:
            AttackPreference = "ranged";
            break;

        case AttackTypes.Both:
            AttackPreference = ObtainAttackPreference();
            break;
        }

        stateMachine = new StateMachine();

        //States
        var patrol        = new Patrol(enemy, navMeshAgent);
        var chase         = new Chase(enemy, transform, Target.transform, navMeshAgent);
        var melee_attack  = new MeleeAttack(enemy, navMeshAgent, Target, transform);
        var ranged_attack = new RangedAttack(enemy, navMeshAgent, Target, transform);
        var die           = new Die(this, enemy);

        //Normal transitions
        At(patrol, chase, InDetectionRange());
        At(chase, patrol, OutOfDetectionRange());
        At(chase, melee_attack, InMeleeAttack());
        At(chase, ranged_attack, InRangedAttack());
        At(melee_attack, chase, OutOfAttackRange());
        At(melee_attack, ranged_attack, InRangedAttack());
        At(ranged_attack, chase, OutOfAttackRange());
        At(ranged_attack, melee_attack, InMeleeAttack());

        //Transitions that can happen at any time
        stateMachine.AddAnyTransition(die, IsDead());

        //Set initial state
        stateMachine.SetState(patrol);

        //Definitions
        void At(IState from, IState to, Func <bool> condition) => stateMachine.AddTransition(from, to, condition);
        Func <bool> InDetectionRange() => () => Vector3.Distance(transform.position, Target.transform.position) <= enemy.enemyData.DetectRange;
        Func <bool> OutOfDetectionRange() => () => Vector3.Distance(transform.position, Target.transform.position) > enemy.enemyData.DetectRange;
        Func <bool> InMeleeAttack() => () => Vector3.Distance(transform.position, Target.transform.position) <= enemy.enemyData.AttackRange && AttackPreference == "melee";
        Func <bool> InRangedAttack() => () => Vector3.Distance(transform.position, Target.transform.position) <= enemy.enemyData.AttackRange && AttackPreference == "ranged";
        Func <bool> OutOfAttackRange() => () => Vector3.Distance(transform.position, Target.transform.position) > enemy.enemyData.AttackRange;
        Func <bool> IsDead() => () => CurrentHealth <= 0;
    }
Example #22
0
    private void Start()
    {
        stateMachine = new StateMachine();
        stateMachine.OnStateEntered += StateMachineOnOnStateEntered;
        stateMachine.OnStateExited  += StateMachineOnStateExited;
        var player                      = GetComponent <Player>();
        var obeliskSelector             = new PhysicsLayerStrategy(LayerMask.GetMask("Obelisk"), 1f);
        var emptyObeliskMouseSelector   = new MouseOverSelector(obeliskSelector, 1, IsObeliskEmpty);
        var infusedObeliskMouseSelector = new MouseOverSelector(obeliskSelector, 1, IsObeliskFull);
        var idle   = new Idle();
        var absorb = new Extract(player, infusedObeliskMouseSelector);
        var exude  = new Infuse(player, emptyObeliskMouseSelector);

        var placingObelisk = new PlacingObelisk(obeliskPrefab, player);

        var invokeFireElement  = new InvokeElement(EssenceNames.Fire);
        var invokeWaterElement = new InvokeElement(EssenceNames.Water);
        var invokeEarthElement = new InvokeElement(EssenceNames.Earth);
        var invokeAirElement   = new InvokeElement(EssenceNames.Air);

        var buildingFireElement  = new Building(emptyObeliskMouseSelector, EssenceNames.Fire);
        var buildingWaterElement = new Building(emptyObeliskMouseSelector, EssenceNames.Water);
        var buildingEarthElement = new Building(emptyObeliskMouseSelector, EssenceNames.Earth);
        var buildingAirElement   = new Building(emptyObeliskMouseSelector, EssenceNames.Air);

        var attack = new Attack(fireAttack);

        stateMachine.AddAnyTransition(placingObelisk, () => PlayerInput.Instance.ObeliskKeyDown);
        stateMachine.AddTransition(placingObelisk, idle, () => PlayerInput.Instance.ObeliskKeyDown || placingObelisk.Finished || PlayerInput.Instance.SecondaryActionKeyDown);

        stateMachine.AddAnyTransition(absorb, () => PlayerInput.Instance.SecondaryActionKeyDown && player.CurrentEssence == null && absorb.CanExtract);
        stateMachine.AddTransition(absorb, idle, () => PlayerInput.Instance.SecondaryActionKeyUp || absorb.Finished);

        stateMachine.AddAnyTransition(invokeFireElement, () => PlayerInput.Instance.InvokeFireDown && player.CurrentEssence == null);
        stateMachine.AddAnyTransition(invokeWaterElement, () => PlayerInput.Instance.InvokeWaterDown && player.CurrentEssence == null);
        stateMachine.AddAnyTransition(invokeEarthElement, () => PlayerInput.Instance.InvokeEarthDown && player.CurrentEssence == null);
        stateMachine.AddAnyTransition(invokeAirElement, () => PlayerInput.Instance.InvokeAirDown && player.CurrentEssence == null);

        stateMachine.AddTransition(invokeFireElement, idle, () => PlayerInput.Instance.InvokeFireDown || PlayerInput.Instance.SecondaryActionKeyDown);
        stateMachine.AddTransition(invokeWaterElement, idle, () => PlayerInput.Instance.InvokeWaterDown || PlayerInput.Instance.SecondaryActionKeyDown);
        stateMachine.AddTransition(invokeEarthElement, idle, () => PlayerInput.Instance.InvokeEarthDown || PlayerInput.Instance.SecondaryActionKeyDown);
        stateMachine.AddTransition(invokeAirElement, idle, () => PlayerInput.Instance.InvokeAirDown || PlayerInput.Instance.SecondaryActionKeyDown);

        stateMachine.AddTransition(invokeFireElement, buildingFireElement, () => CanStartBuilding(emptyObeliskMouseSelector));
        stateMachine.AddTransition(invokeWaterElement, buildingWaterElement, () => CanStartBuilding(emptyObeliskMouseSelector));
        stateMachine.AddTransition(invokeEarthElement, buildingEarthElement, () => CanStartBuilding(emptyObeliskMouseSelector));
        stateMachine.AddTransition(invokeAirElement, buildingAirElement, () => CanStartBuilding(emptyObeliskMouseSelector));

        stateMachine.AddTransition(buildingFireElement, invokeFireElement, () => PlayerInput.Instance.PrimaryActionKeyUp || buildingFireElement.Finished);
        stateMachine.AddTransition(buildingWaterElement, invokeWaterElement, () => PlayerInput.Instance.PrimaryActionKeyUp || buildingWaterElement.Finished);
        stateMachine.AddTransition(buildingEarthElement, invokeEarthElement, () => PlayerInput.Instance.PrimaryActionKeyUp || buildingEarthElement.Finished);
        stateMachine.AddTransition(buildingAirElement, invokeAirElement, () => PlayerInput.Instance.PrimaryActionKeyUp || buildingAirElement.Finished);


        stateMachine.AddTransition(idle, exude, () => PlayerInput.Instance.PrimaryActionKeyDown && player.CurrentEssence != null && exude.CanInfuse);
        stateMachine.AddTransition(exude, idle, () => PlayerInput.Instance.PrimaryActionKeyUp || exude.Finished);

        stateMachine.AddTransition(idle, attack, () => PlayerInput.Instance.AttackActionKeyDown && player.CurrentEssence != null);
        stateMachine.AddTransition(attack, idle, () => PlayerInput.Instance.AttackActionKeyUp);

        stateMachine.SetState(idle);
    }
Example #23
0
    private void Awake()
    {
        GetComponentInChildren <MonsterAnimatorEvents>().ParentbasicEnemy = this;
        var rbs = GetComponentsInChildren <Rigidbody>();

        foreach (var rb in rbs)
        {
            rb.isKinematic = true;
        }

        navMeshAgent                = GetComponent <NavMeshAgent>();
        animator                    = GetComponentInChildren <Animator>();
        playerMovementCollider      = GetComponentInChildren <Collider>();
        eyesPosition                = GetComponentInChildren <EyesLocation>().transform;
        wanderArea                  = GetComponentInChildren <BoxCollider>();
        wanderArea.transform.parent = null;
        SetBoxBounds(wanderArea, out wanderAreaBoundsMin, out wanderAreaBoundsMax);

        stateMachine = new StateMachine();

        //STATES
        var idle            = new Idle(this);
        var chasePlayer     = new ChasePlayer(this);
        var dead            = new Dead(this, playerMovementCollider);
        var attack          = new Attack(this);
        var wander          = new Wander(this);
        var wanderInArea    = new WanderInArea(this);
        var searchForPlayer = new SearchForPlayer(this);
        var searchForSound  = new SearchForSound(this);
        var lookForSound    = new LookForSound(this);

        //TRANSITIONS
        AT(idle, chasePlayer, SeePlayer());
        AT(wander, chasePlayer, SeePlayer());
        AT(wanderInArea, chasePlayer, SeePlayer());
        AT(searchForPlayer, chasePlayer, SeePlayer());
        AT(searchForSound, chasePlayer, SeePlayer());

        AT(idle, lookForSound, HearsPlayer());
        AT(wander, lookForSound, HearsPlayer());
        AT(wanderInArea, lookForSound, HearsPlayer());
        AT(lookForSound, searchForSound, TimeToGoToSound());

        AT(chasePlayer, attack, InAttackRange());
        AT(attack, wanderInArea, AttackDone());
        AT(chasePlayer, searchForPlayer, CantFindPlayer());
        AT(searchForPlayer, wanderInArea, SearchOver());
        AT(chasePlayer, wanderInArea, LoseAgro());



        //ANY TRANSITIONS
        stateMachine.AddAnyTransition(dead, Dead());
        //stateMachine.AddAnyTransition(idle, PlayerMissing());

        //BEGINNING STATE
        stateMachine.SetState(wanderInArea);

        void AT(State to, State from, Func <bool> condition) => stateMachine.AddTransition(to, from, condition);
        Func <bool> Dead() => () => currentHealth <= 0;
        Func <bool> PlayerMissing() => () => Player.instance == null;
        Func <bool> PlayerIsClose() => () => Vector3.Distance(transform.position, Player.instance.transform.position) < 7;
        Func <bool> LoseAgro() => () => Vector3.Distance(transform.position, Player.instance.transform.position) > 50;
        Func <bool> AttackDone() => () => attack.time >= attackTime;
        Func <bool> InAttackRange() => () => Vector3.Distance(transform.position, Player.instance.transform.position) < attackAttemptRange;
        Func <bool> SeePlayer() => () => RayHitsPlayer() && Vector3.Angle(eyesPosition.forward, Player.instance.mainCamera.transform.position - eyesPosition.position) < sightFOV;
        Func <bool> CantFindPlayer() => () => !RayHitsPlayer();
        Func <bool> SearchOver() => () => searchForPlayer.searchTime >= maxSearchTime;
        Func <bool> HearsPlayer() => () => Hearing();

        Func <bool> TimeToGoToSound() => () =>
        {
            return(timeSinceHeard >= reactionTime);
        };
    }
    protected void Awake()
    {
        anim         = GetComponent <Animator>();
        Shaker       = GameObject.FindGameObjectWithTag("Shake");
        maxGrip      = fighter.weight;
        HP           = fighter.HitPoints;
        jumpHeight   = fighter.jumpHeight;
        moveSpeed    = fighter.speed;
        maxJumpCount = fighter.jumpCount;
        rigidBody    = GetComponent <Rigidbody2D>();
        Target       = GameObject.FindGameObjectWithTag("Floor").GetComponent <GravAttractor>();
        Shield       = GetComponentInChildren <Barrier>(true).gameObject;
        if (isPlayer)
        {
            player = ReInput.players.GetPlayer(playerID); //The player controlling this fighter
        }
        gameObject.name = fighter.name.ToString() + playerID;
        statemachine    = new StateMachine();
        var flinch       = new Flinch(this);
        var walk         = new Walk(this);
        var run          = new Run(this);
        var idle         = new Idle(this);
        var jump         = new Jump(this);
        var groundattack = new GroundAttack(this, attack);
        var airattack    = new AirAttack(this, attack);
        var stun         = new Stun(this);
        var leapprep     = new LeapPrep(this);
        var blocking     = new Blocking(this);
        var dodge        = new AirDodge(this);
        var leap         = new Leaping(this);
        var prone        = new Prone(this);

        At(dodge, idle, landed());
        At(flinch, idle, stunless());
        At(run, idle, stop());
        At(walk, idle, stop());
        At(idle, jump, jumping());
        At(idle, jump, unground());
        At(jump, jump, jumping());
        At(walk, jump, unground());
        At(run, jump, unground());
        At(walk, jump, jumping());
        At(run, jump, jumping());
        At(walk, run, running());
        At(run, walk, walking());
        At(idle, walk, walking());
        At(idle, run, running());
        At(idle, groundattack, offensive());
        At(walk, groundattack, offensive());
        At(run, groundattack, offensive());
        At(jump, airattack, offensive());
        At(groundattack, idle, unoffensive());
        At(airattack, jump, unoffensive());
        At(airattack, idle, landed());
        At(jump, airattack, offensive());
        At(jump, idle, landed());
        At(jump, dodge, guard());
        At(blocking, stun, pierce());
        At(idle, blocking, guard());
        At(walk, blocking, guard());
        At(run, blocking, guard());
        At(leapprep, idle, cancelleap());
        At(leapprep, leap, gravityChange());
        At(blocking, idle, unguard());
        At(leap, idle, landed());
        At(prone, idle, stunless());
        statemachine.AddAnyTransition(leapprep, () => LeapPrep && leapCooldown <= 0);
        statemachine.AddAnyTransition(stun, () => stunned);
        statemachine.AddAnyTransition(flinch, () => isDamaged);
        statemachine.AddAnyTransition(prone, () => slam);
        Func <bool> stunless() => () => doneStun == true;
        Func <bool> walking() => () => speed > 0.3 && speed < 0.7;
        Func <bool> running() => () => speed > 0.7;
        Func <bool> stop() => () => speed < 0.3;
        Func <bool> jumping() => () => (jumpTimer > Time.time) && (maxJumpCount > jumpCount) && !action && actionCooldown > 0;
        Func <bool> offensive() => () => attack != null && actionCooldown > 0;
        Func <bool> unoffensive() => () => attack == null;
        Func <bool> landed() => () => grounded;
        Func <bool> pierce() => () => Guard <= 0;
        Func <bool> guard() => () => isBlocking && actionCooldown > 0;
        Func <bool> unguard() => () => !isBlocking;
        Func <bool> gravityChange() => () => LeapRelease;
        Func <bool> cancelleap() => () => cancelled;
        Func <bool> unground() => () => !grounded;

        statemachine.SetState(idle);
    }
    private void Awake()
    {
        agent        = GetComponent <NavMeshAgent>();
        inventory    = new Inventory(inventorySize);
        stateMachine = new StateMachine();

        //states
        IdleState            idleState       = new IdleState(this);
        MoveToPointState     moveToPoint     = new MoveToPointState(this, agent);
        MoveToResourceState  toResource      = new MoveToResourceState(this, agent);
        MoveToBuildsite      moveToBuild     = new MoveToBuildsite(this, agent);
        HarvestResourceState harvestResource = new HarvestResourceState(this);
        FindStorageState     findStorage     = new FindStorageState(this);
        FindResourceState    findResource    = new FindResourceState(this, agent);
        MoveToStorageState   toStorage       = new MoveToStorageState(this, agent);
        StoreItemsState      storeItems      = new StoreItemsState(this);
        BuildState           buildState      = new BuildState(this);

        stateMachine.SetState(idleState);

        //transitions
        AddNewTransition(moveToPoint, idleState, Stuck());
        AddNewTransition(idleState, toResource, HasRTarget());
        AddNewTransition(idleState, moveToBuild, HasBuildTarget());
        AddNewTransition(toResource, harvestResource, ReachedResource());
        AddNewTransition(harvestResource, findStorage, InventoryFull());
        AddNewTransition(harvestResource, findResource, ResourceIsEmpty());
        AddNewTransition(findStorage, toStorage, HasStoreTarget());
        AddNewTransition(toStorage, storeItems, ReachedStorage());
        AddNewTransition(storeItems, findStorage, cantStore());
        AddNewTransition(storeItems, toResource, GatherAndTarget());
        AddNewTransition(storeItems, findResource, GatherAndNoTarget());
        AddNewTransition(findResource, toResource, HasRTarget());
        AddNewTransition(findResource, idleState, NoResourceNearbyEmpty());
        AddNewTransition(findResource, findStorage, NoResourceNearbyNotEmpty());
        AddNewTransition(moveToBuild, buildState, ReachedBuildsite());
        AddNewTransition(buildState, idleState, () => buildTarget == null);

        stateMachine.AddAnyTransition(idleState, () => currentTask == unitTask.None);
        stateMachine.AddAnyTransition(moveToPoint, () => clickMove);
        AddNewTransition(moveToPoint, idleState, ReachedPoint());

        void AddNewTransition(IState fromState, IState toState, Func <bool> condition) => stateMachine.AddTransition(fromState, toState, condition);

        //condition functions
        Func <bool> Stuck() => () => moveToPoint.stuckTime > 0.8f;
        Func <bool> HasRTarget() => () => resourceTarget != null;
        Func <bool> HasStoreTarget() => () => storeTarget != null;
        Func <bool> HasBuildTarget() => () => buildTarget != null;
        Func <bool> ReachedPoint() => () => Vector3.Distance(transform.position, clickTarget) < stopDistance;
        Func <bool> ReachedResource() => () => resourceTarget != null && Vector3.Distance(transform.position, resourceTarget.transform.position) < stopDistance;
        Func <bool> ReachedBuildsite() => () => buildTarget != null && Vector3.Distance(transform.position, buildTarget.transform.position) < stopDistance;
        Func <bool> ResourceIsEmpty() => () => resourceTarget == null;
        Func <bool> InventoryFull() => () => !inventory.CanAdd(resourceItem);
        Func <bool> ReachedStorage() => () => Vector3.Distance(transform.position, storeTarget.transform.position) < stopDistance;
        Func <bool> cantStore() => () => storeTarget == null && inventory.container.Count > 0;
        Func <bool> GatherAndTarget() => () => inventory.container.Count == 0 && resourceTarget != null;
        Func <bool> GatherAndNoTarget() => () => inventory.container.Count == 0 && resourceTarget == null && currentTask == unitTask.Gather;
        Func <bool> NoResourceNearbyEmpty() => () => inventory.container.Count == 0 && resourceTarget == null && nearbyRescources.Count == 0;
        Func <bool> NoResourceNearbyNotEmpty() => () => inventory.container.Count > 0 && resourceTarget == null;
    }
Example #26
0
 protected void AddAnyTransition(IState to, ICondition condition)
 {
     stateMachine.AddAnyTransition(to, condition);
 }