public void AddLinkTo(string toState, StateDelegate logic) { if(logic == null && !links.ContainsKey(toState)) {Debug.Log("Add StateLink Error"); return;} links.Add (toState, logic); }
protected virtual void AttackingState() { stateIndicator = "attacking"; UpdateAssistTargetting(); if (attackTarget == null) { stateDelegate = IdleState; } else { if (TargetInRange()) { setRails(false); // TODO use coroutine for attack cooldown if (ReadyToAttack()) { Attack(); } } else { setRails(true); // Move towards the enemy //navigationController.registerClick(this, attackTarget.transform.position); Move(); } } }
public void UnsetStateDelegate(int state, StateDelegate @delegate) { if (_delegates.ContainsKey(state)) { _delegates[state].Remove(@delegate); } }
public virtual float UpdateActiveState() { float thefloat = -1; if (!IsEmpty() && !blockStateMachine) { StateDelegate active_state = m_stateStack[m_stateStack.Count - 1]; bool resumeLoop = true; while (resumeLoop) { resumeLoop = false; thefloat = active_state(); if (active_state != m_stateStack[m_stateStack.Count - 1] && KnightContext.instance.AutonomousUnits) { // TODO aherrera : is there some sort of "exit state" function I should call? Debug.Log("FSM -- Resuming FSM loop"); active_state = GetActiveState(); resumeLoop = true; } } } return(thefloat); }
public State(int enumIndex, StateDelegate enterD, StateDelegate updateD, StateDelegate exitD) { key = enumIndex; enter = enterD; update = updateD; exit = exitD; }
public void DisconnectToDelegate(string key, StateDelegate value) { if (ContainsKey(key)) { Values[Keys.IndexOf(key)] -= value; } }
/// <summary> /// Push a new state to the Top of the stack /// </summary> /// <param name="newActiveState"></param> public void Push(StateDelegate newActiveState) { if (GetActiveState() != newActiveState) { Debug.Log("FSM -- Adding new ActiveState: " + newActiveState.ToString()); m_stateStack.Add(newActiveState); } }
void OnPrintingProgress(float amount) { if (Mathf.Approximately(amount, 1.0f)) { HandleMenu = NormalMenu; Dispatcher <float> .RemoveListener(PrinterController.kOnPrintingProgress, OnPrintingProgress); } }
protected virtual void Start() { _rb = GetComponent <Rigidbody2D>(); _anim = GetComponent <Animator>(); SetPatrolState(); SetChaseState(); State = Patrol; }
protected virtual void CheckDeath() { if (_hp <= 0) { State = CheckDeath; _rb.velocity = Vector2.up * _rb.velocity.y; _anim.Play("Dying"); } }
public void SetDelegateForState(int state, StateDelegate @delegate) { if (!_delegates.ContainsKey(state)) { _delegates[state] = new List <StateDelegate>(); } _delegates[state].Add(@delegate); }
// // State utility function implementations // /** * Initialise a simplehsm state machine. * * @param topState The topmost (and initial) state of the hierarchy * */ protected void Initialize(StateDelegate topState) { // init top state this.topState = topState; // init deep history table deepHistoryTable.Clear(); // transition to initial top state InitTransitionState(topState); }
protected void Add(StateDelegate state) { var index = IndexOf(state.Method); if (index == Const.INDEX_NONE) { states.Add(new StateInfo(state)); } }
public void StateDeadUpdate(GameTime gameTime) { if (gameTime.TotalGameTime.Seconds - _timer.Seconds >= 3) { _timer = gameTime.TotalGameTime; _stateDelegate = StateInvincibleUpdate; PlayerAnimation.Active = true; PlayerAnimation.Color = Color.Red; } }
public void Initialize(Game1 game, Animation animation, Vector2 position) { PlayerAnimation = animation; _position = position; Health = 100; _stateDelegate = StateAliveUpdate; _game = game; }
protected virtual void MovingState() { stateIndicator = "moving"; setRails(true); Move(); if (path == null && navTarget == Vector3.zero) { stateDelegate = IdleState; } }
private static void HellowLambda() { StateDelegate stateDelegate = str => { string s = str += "Lambda"; MessageBox.Show(s); }; stateDelegate("Hello "); }
public DelegateTriggerMachine <TTrigger, TEnumComparer> Connect(StateDelegate source, TTrigger trigger, StateDelegate destination) { Add(source); Add(destination); var transitions = connections.SafeGet(source.Method); transitions[trigger] = destination.Method; return(this); }
private void StateAliveUpdate(GameTime gameTime) { if (Health <= 0) { _timer = gameTime.TotalGameTime; _game.AddExplosion(_position); PlayerAnimation.Active = false; _stateDelegate = StateDeadUpdate; } PlayerAnimation.Position = _position; }
public void StateInvincibleUpdate(GameTime gameTime) { if (gameTime.TotalGameTime.Seconds - _timer.Seconds >= 3) { PlayerAnimation.Color = Color.White; Health = 100; _stateDelegate = StateAliveUpdate; } PlayerAnimation.Position = _position; }
/** * Check is one state is the parent of another. * * @param parentState The parent state to check * @param childState The child state to check * @return True if the parentState parameter is a parent to the childState parameter * */ protected Boolean IsParent(StateDelegate parentState, StateDelegate childState) { do { childState = childState(new StateEvent(Signal.Null)); if (childState == parentState) { return(true); } }while (childState != null); return(false); }
/** * Record deep history psuedostate. * * @param historyParent The parent state of the deep history psuedostate * @param historyState The state to return to if transitioning to the deep history psuedostate * */ void RecordDeephist(StateDelegate historyParent, StateDelegate historyState) { for (int i = 0; i < deepHistoryTable.Count; i++) { if (deepHistoryTable[i].Parent == historyParent) { deepHistoryTable[i] = new DeepHistoryEntry(historyParent, historyState); return; } } deepHistoryTable.Add(new DeepHistoryEntry(historyParent, historyState)); }
protected virtual void FollowingState() { stateIndicator = "following"; if (assistTarget == null || LeaderInRange()) { stateDelegate = IdleState; } else { UpdateAssistTargetting(); Move(); } }
/** * Check if a state machine is currently in a certain state. * * @param state The state to check * @return True if the state machine is currently in the specified state * */ protected Boolean IsInState(StateDelegate state) { StateDelegate parentState = curState; do { if (state == parentState) { return(true); } parentState = parentState(new StateEvent(Signal.Null)); }while (parentState != null); return(false); }
public StateDelegate GetActiveState() { StateDelegate returnVal = null; if (m_stateStack.Count > 0) { returnVal = m_stateStack[m_stateStack.Count - 1]; } if (returnVal == null) { Debug.LogWarning("FSM -- returning a null ActiveState"); } return(returnVal); }
/// <summary> /// 初始化代委托理事件 /// </summary> private void InitDelegateEvent() { m_JoyStick = GameObject.FindObjectOfType<JoyStick>(); m_JoyStick.OnJoyStickTouchBegin += OnTouchBegin; m_JoyStick.OnJoyStickTouchMove += OnTouchMove; m_JoyStick.OnJoyStickTouchEnd += OnTouchEnd; m_ButtonEvent = GameObject.FindObjectOfType<FightButtonEvent>(); m_ButtonEvent.OnAttack += OnAttack; m_ButtonEvent.OnJump += OnJump; m_ButtonEvent.OnSkill += OnSkill; m_PlayerState = GameObject.FindObjectOfType<StateDelegate>(); m_PlayerState.OnStateChange += SwitchPlayerState; }
//Take Damage public virtual void Hit(UnitController attacker) { health -= attacker.attackStr; anim.flinchAnim(); if (attackTarget == null) { attackTarget = attacker; stateDelegate = AttackingState; } if (!attackers.Contains(attacker)) { attackers.Add(attacker); } }
/** * Retrive deep history psuedostate. * * @param historyParent The parent state of the deep history psuedostate * @return The state to transition to via the deep history psuedostate * */ private StateDelegate RetrieveDeephist(StateDelegate historyParent) { for (int i = 0; i < deepHistoryTable.Count; i++) { if (deepHistoryTable[i].Parent == historyParent) { StateDelegate res = deepHistoryTable[i].Child; // remove history state from deep history table deepHistoryTable.RemoveAt(i); // return deep history target return(res); } } return(null); }
/** * Send a signal to the state machine. * * @param e The event to send to the state machine * */ public void SignalCurrentState(StateEvent e) { if (curState != null) { StateDelegate parentState = curState; do { parentState = parentState(e); }while (parentState != null); } else { System.Console.WriteLine("SignalCurrentState: ERROR - current state is invalid!\n"); } }
public void AddState(string stateName, StateDelegate begin, StateDelegate tick, StateDelegate end) { StateInfo info = new StateInfo(); info.OnBegin = begin; info.OnTick = tick; info.OnEnd = end; states.Add(stateName, info); // If no states have been set yet, this state becomes the initial state. if (currentStateName == null) { State = stateName; } }
public void SubscribeState(StateDelegate stateDelegate) { if (StateDelegatesList == null) { StateDelegatesList = new List <StateDelegate>(); } if (!StateDelegatesList.Contains(stateDelegate)) { StateDelegatesList.Add(stateDelegate); } else { Debug.Log("Already subscribed: " + stateDelegate.ToString()); } }
public void UnsubscribeState(StateDelegate stateDelegate) { if (StateDelegatesList == null) { Debug.Log("Nothing subscribed yet, subscribe first!"); } if (StateDelegatesList.Contains(stateDelegate)) { StateDelegatesList.Remove(stateDelegate); } else { Debug.Log("Already removed: " + stateDelegate.ToString()); } }
/** * Initiate an initial transition to a new state (this function should only be used from a #SimpleHsm::Signal::Init state event). * * @param newState The state to transition to * */ protected void InitTransitionState(StateDelegate newState) { // set new state curState = newState; if (curState != null) { // entry signal to current state curState(new StateEvent(Signal.Entry)); // init signal to current state curState(new StateEvent(Signal.Init)); } else { System.Console.WriteLine("InitTransitionState: ERROR - current state is invalid!\n"); } }
public void SwitchStates(StateDelegate enter, StateDelegate update, StateDelegate exit, string name){ string switchDebug = "STATE TRANSITION: "; if (this.exit != null){ switchDebug += this.currentState + " "; this.exit(); //exit the current state } //set up the new state this.enter = enter; this.update = update; this.exit = exit; this.currentState = name; if (this.enter != null){ switchDebug += "--> " + name; this.enter(); //enter the new state } Debug.Log(switchDebug); }
public DeepHistoryEntry(StateDelegate parent, StateDelegate state) { Parent = parent; Child = state; }
/** * Check if a state delegates method has the DeepHistory attribute * * @param state The state to check * @return True if the method refered to by the delegate has the DeepHistory attribute * */ protected bool HasDeepHistAttrib(StateDelegate state) { return state.Method.GetCustomAttributes(typeof(DeepHistory), false).Length > 0; }
// Utility method for performing the state delegate swapping logic based on an enum value void SwitchCurrentState(MState state) { this.mState = state; switch (mState) { case MState.None: currentStateMethod = null; break; case MState.Entering: currentStateMethod = this.enter; break; case MState.Exiting: currentStateMethod = this.exit; break; case MState.Updating: currentStateMethod = this.update; break; } }
// A single state may be stored at any given time. If you need to queue more than // one state, you could conceivably replace ChangeState() with AddState() and append // the three state parameters to a list. As its currently written, changing the state // immediatley calls the current 'exit' state, then overwrites the cached enter/run/exit // states with these new states. public void ChangeState(StateDelegate enter, StateDelegate update, StateDelegate exit) { bool isStateCurrentlyRunning = currentStateMethod != null; // If a state is currently running, it should be allowed to gracefully exit // before the next state takes over if (isStateCurrentlyRunning) { SwitchCurrentState (MState.Exiting); } // Cache the given state values this.enter = enter; this.update = update; this.exit = exit; // If a state isn't currently running, we can immediately switch to our entering // state using the state delegates we cached a few lines above if (!isStateCurrentlyRunning) { SwitchCurrentState (MState.Entering); } if (immediateMode) { Execute(); } }
/** * Check if a state machine is currently in a certain state. * * @param state The state to check * @return True if the state machine is currently in the specified state * */ protected Boolean IsInState(StateDelegate state) { StateDelegate parentState = curState; do { if (state == parentState) return true; parentState = parentState(new StateEvent(Signal.Null)); } while (parentState != null); return false; }
// Call this during public void Execute() { if (currentStateMethod == null) return; _shouldQuit = false; int loops = 0; while(!_shouldQuit) { // Execute the current state method bool finished = currentStateMethod (); // If we've reached the end of the current enter/run/exit, advance to the next one if (finished && !_shouldQuit) { switch (mState) { case MState.None: SwitchCurrentState (MState.Entering); break; case MState.Entering: SwitchCurrentState (MState.Updating); enter = null; _shouldQuit = true; break; case MState.Updating: SwitchCurrentState (MState.Exiting); update = null; break; case MState.Exiting: // If an Enter behavior exists, it must have been added by ChangeState. We should // start running again from the top instead of coming to a halt. if (enter != null) { SwitchCurrentState (MState.Entering); } else { SwitchCurrentState (MState.None); exit = null; _shouldQuit = true; } break; } } else { _shouldQuit = true; } loops++; if (loops >= maxLoops) { _shouldQuit = true; // This keeps us from freezing due to an infinite exit/enter cycle Debug.LogError("A statemachine has reached the maximum loop count!"); } if (!immediateMode) { _shouldQuit = true; } } }
/** * Initiate a transition to a new state. * * @param newState The state to transition to * */ protected void TransitionState(StateDelegate newState) { TransitionState(newState, false); }
/** * Initiate an initial transition to a new state (this function should only be used from a #SimpleHsm::Signal::Init state event). * * @param newState The state to transition to * */ protected void InitTransitionState(StateDelegate newState) { // set new state curState = newState; if (curState != null) { // entry signal to current state curState(new StateEvent(Signal.Entry)); // init signal to current state curState(new StateEvent(Signal.Init)); } else System.Console.WriteLine("InitTransitionState: ERROR - current state is invalid!\n"); }
/** * Initiate a transition to a new state. * * This function will: * - replace the target state with the deep history target if required * - store a deep history target state if exiting a composite state with a deep history child * - perform the exit/entry chain from the current state to the target state * * @param newState The state to transition to * @param toDeepHist Whether to transition to the states internal deep history psuedostate * */ protected void TransitionState(StateDelegate newState, bool toDeepHist) { // retrive historical state if appropriate if (toDeepHist) { newState = RetrieveDeephist(newState); if (newState == null) { System.Console.WriteLine("TransitionState: ERROR - RetrieveDeephist failed!"); return; } } // exit signal to current state if (curState != null) { StateDelegate parentState; // record the deep history state if appropriate parentState = curState(new StateEvent(Signal.Null)); while (parentState != null) { // the top state cannot have a history sub state and returns stnone to all // unhandled signals anyhow if (parentState == topState) break; // if the parentState has the DeepHist attribute and is not a parent of the new // state then record the deep history else if (HasDeepHistAttrib(parentState) && !IsParent(parentState, newState)) { RecordDeephist(parentState, curState); break; } parentState = parentState(new StateEvent(Signal.Null)); } // state exit chain curState(new StateEvent(Signal.Exit)); parentState = curState(new StateEvent(Signal.Null)); while (!IsParent(parentState, newState)) { parentState(new StateEvent(Signal.Exit)); parentState = parentState(new StateEvent(Signal.Null)); } // set current state to parent state curState = parentState; } else System.Console.WriteLine("TransitionState: ERROR - current state is invalid!"); // entry signal to new state while (curState != newState) { StateDelegate parentState = newState; StateDelegate lastChild = newState; while (true) { parentState = parentState(new StateEvent(Signal.Null)); if (parentState == curState) { lastChild(new StateEvent(Signal.Entry)); // set current state to last child state curState = lastChild; break; } lastChild = parentState; } } // init signal to new state newState(new StateEvent(Signal.Init)); }
/** * Retrive deep history psuedostate. * * @param historyParent The parent state of the deep history psuedostate * @return The state to transition to via the deep history psuedostate * */ private StateDelegate RetrieveDeephist(StateDelegate historyParent) { for (int i = 0; i < deepHistoryTable.Count; i++) { if (deepHistoryTable[i].Parent == historyParent) { StateDelegate res = deepHistoryTable[i].Child; // remove history state from deep history table deepHistoryTable.RemoveAt(i); // return deep history target return res; } } return null; }
public State(string name, StateDelegate enterMethod) { _name = name; _enter = enterMethod; }
/** * Check is one state is the parent of another. * * @param parentState The parent state to check * @param childState The child state to check * @return True if the parentState parameter is a parent to the childState parameter * */ protected Boolean IsParent(StateDelegate parentState, StateDelegate childState) { do { childState = childState(new StateEvent(Signal.Null)); if (childState == parentState) return true; } while (childState != null); return false; }