public void Update(float deltaTime) { this.CheckPossibleNextStates(); _currentState.Update(deltaTime); _elapsedTimeInCurrentState += deltaTime; bool shouldExit = _currentState.CheckIfShouldExit(); bool shouldExitFromTime = _currentState.CheckIfShouldExitFromFiniteTime(); if (shouldExit || shouldExitFromTime) { TransitionMap currentTransitionMap = _transitions[_currentState.GetType()]; if (currentTransitionMap.PossibleStatesToTransitionTo.Count <= 0) { Debug.LogError("FiniteStateMachine::Update - current state attempting to exit, missing transitions to exit to."); return; } List <System.Type> possibleStatesToTransitionTo = currentTransitionMap.PossibleStatesToTransitionTo; if (shouldExitFromTime) { possibleStatesToTransitionTo = possibleStatesToTransitionTo.Where(type => _states[type].IsFinite).ToList(); } System.Type nextStateType = possibleStatesToTransitionTo.PickRandom(); FSMState <T> nextState = _states[nextStateType]; this.ChangeState(nextState); } }
public void AddState(FSMState <T> state) { state.SetupWithMachineAndContext(this, _context); _states[state.GetType()] = state; TransitionMap transitionMap = new TransitionMap(); transitionMap.PossibleStatesToTransitionTo = new List <System.Type>(); transitionMap.PossibleStatesToTransitionFrom = new List <System.Type>(); _transitions[state.GetType()] = transitionMap; }
protected bool CheckPossibleNextStates() { TransitionMap currentTransitionMap = _transitions[_currentState.GetType()]; foreach (System.Type stateType in currentTransitionMap.PossibleStatesToTransitionTo) { FSMState <T> state = _states[stateType]; bool shouldTakeover = state.CheckIfShouldTakeoverCurrentState(); if (shouldTakeover) { this.ChangeState(state); return(true); } } return(false); }
public void AddTransition(FSMState <T> state, FSMState <T> otherState) { System.Type stateType = state.GetType(); System.Type otherStateType = otherState.GetType(); if (!_transitions.ContainsKey(stateType) || !_transitions.ContainsKey(otherStateType)) { Debug.LogError("FiniteStateMachine::AddTransition - Invalid state types!"); return; } TransitionMap transitionMap = _transitions[stateType]; TransitionMap otherTransitionMap = _transitions[otherStateType]; if (transitionMap.PossibleStatesToTransitionTo.Contains(otherStateType) || otherTransitionMap.PossibleStatesToTransitionFrom.Contains(stateType)) { Debug.LogError("FiniteStateMachine::AddTransition - State already found inside possible states to transition to!"); return; } transitionMap.PossibleStatesToTransitionTo.Add(otherStateType); otherTransitionMap.PossibleStatesToTransitionFrom.Add(stateType); }