public void InitCommendSlots(FSM targetFsm, HeroCharacter heroCharacter) { itemSlotDisplay.Init(targetFsm, heroCharacter); /* skillDisplay.Init(targetFsm, heroCharacter); */ }
public void Inizializza(FSM oggetto) { MioCervello = oggetto; if (!MioCervello.DatiPersonaggio.Giocabile) elencoPercorsiDisponibili = Statici.databaseInizialePercorsi.trovaPercorsiDaPersonaggio(MioCervello.DatiPersonaggio.miaClasse); if (elencoPercorsiDisponibili.Count > 0) MioCervello.IndexPercorso = elencoPercorsiDisponibili[Random.Range(0, elencoPercorsiDisponibili.Count)]; //per ora gli assegno percorso casuale...da sistemare e completare // foreach (int elem in elencoPercorsiDisponibili) // Debug.Log("classe" + MioCervello.DatiPersonaggio.miaClasse + " idx " + elem); // Debug.Log("percorso scelto " + MioCervello.IndexPercorso); /* if (GameManager.dizionarioPercorsi.ContainsKey(MioCervello.gameObject.tag)) MioCervello.IndexPercorso = GameManager.dizionarioPercorsi[MioCervello.gameObject.tag]; */ //-Vedere se meglio con impostazione nostra di indiceDestionazioni oppure fare in modo che a ogni chiamata al Gestore PErcorso si incrementa da solo if (MioCervello.IndexPercorso < 0) // { Debug.LogError("Ue' picio.......Non hai stato assegnato nessun percorso..quindi se ne sta fermo in attesa di Input"); return; } Percorso = Statici.padreGestore[MioCervello.IndexPercorso]; indiceDestinazioni = -1; //per convenzione ho assegnato il valore -1 per default (percorso no assegnato) }
protected override void OnStart() { base.OnStart (); this.stateMachine = this.gameObject.AddComponent<FSM> (); this.stateMachine.container = this; }
public UncontrolledFall(FSM fsm) : base(fsm) { // Add Transitions. this.gravity = Hero.Gravity; this.maxSpeed = 0.0f; }
public HeroState(FSM fsm) : base(fsm) { Hero = (HeroMotion)fsm; animator = gameObject.GetComponent<Animator>(); InputManager = gameObject.GetComponent<InputManager>(); }
public MenuInGame2(FSM parentFsm, UIManager2 panel1, UIManager2 panel2) : base(parentFsm, panel1, panel2, "MenuInGame2.fsm") { InitUI(); int stageCode = (int)parentFsm.Variables["stageId"]; }
public BossAlertTrigger(FSM parentFsm) : base(OverlapEventType.Trigger, 1, 1, WorldAnchor.BottomLeft) { Assert.IsTrue(parentFsm != null); this.parentFsm = parentFsm; }
void Awake() { _fsm = new FSM<GameStates>(); AddStates(); AddTransitons(); _instance = this; }
public JumpFall(FSM fsm) : base(fsm) { AddTransition<WallRun>(CanWallRun); this.gravity = Hero.JumpGravity; this.maxSpeed = Hero.MaxAirSpeed; }
public LockObstacle(ObjectField objectField, ObjectStage objectStage, ItemDropManager itemDropManager, FSM parentFsm) : base(objectField, objectStage, itemDropManager, parentFsm) { objectLockObstacle = TableLoader.GetTable<ObjectLockObstacle>().Get(objectStage.ObjectID); int lockCount = objectLockObstacle.LockCount; this.name = StringTableLoader.Instance.Get(objectField.ObjectName); InitStatus<LockStatus>( new object[] { LockStatus.Lock, 0, lockCount, lockCount } ); RegisterDeathCondition( delegate(Status current) { return current.Get(LockStatus.Lock) == 0; } ); AddAction(Action.E_Type.Unlock, delegate(float value, GameInstance firer, string[] param) { FSMEvent("damage"); return new ActionHandler.Result(LockStatus.Lock, -value); } ); AddAction(Action.E_Type.Attack, delegate(float value, GameInstance firer, string[] param) { FSMEvent("damage"); return new ActionHandler.Result(LockStatus.Lock, -1); } ); }
public MenuInGame(FSM parentFsm, UIManager2 panel1, UIManager2 panel2) : base(parentFsm, panel1, panel2, "MenuInGame.fsm") { timeClient = TimeManager.Instance.Create(); InitUI(); int stageId = (int)parentFsm.Variables["stageId"]; /* // ddong if (stageId < 2000) { stageId += 2000; } */ InitStage(stageId, out stageEntity, out gameEntity); Rect fieldArea = UI.GetFieldArea(); field = CreateField(stageEntity, fieldArea, timeClient, fsm); // ddong int subClassCode = 11; int level = 1; int trainLevel = 1; this.subClassEntity = TableLoader.GetTable<SubClassEntity>().Get(subClassCode); ClassLevelEntity levelEntity = TableLoader.GetTable<ClassLevelEntity>().Get(subClassEntity.classCode, level); TrainLevelEntity trainLevelEntity = TableLoader.GetTable<TrainLevelEntity>().Get(subClassEntity.classCode, trainLevel); FieldObjectEntity objectField = TableLoader.GetTable<FieldObjectEntity>().Get(subClassEntity.objectCode); Rect puzzleArea = UI.GetPuzzleArea(); CreatePuzzle(puzzleArea, timeClient, subClassCode, out puzzleRecord, out puzzlePanel); user = CreateUser(stageEntity, UI, fsm); heroCharacter = CreateCharacter(objectField, levelEntity, trainLevelEntity, subClassEntity, user, puzzlePanel, itemDropManager, UI.AddBuffIcon, UI.RemoveBuffIcon, fsm); itemDropManager = new ConsumableSpawn(stageEntity.gameModeCode, levelEntity.consumableTier); Func<float> getLifeDrainRate = (() => gameEntity.defaultHP); new PlayerCharacter(user, heroCharacter, getLifeDrainRate, fsm); /* heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.HP, OnCharacterHPChanged); heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.HP, UI.ChangeHP); heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.MP, UI.ChangeMana); heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.Armor, UI.ChangeShield); */ UI.InitCommendSlots(fsm, heroCharacter); field.AddPlayerCharacter(heroCharacter); field.FocusOnForced(heroCharacter, 0); puzzlePanel.SetQueue(user.commandQueue); var screenPosTable = TableLoader.GetTable<ScreenPositionEntity2>(); var hpToPos = screenPosTable.Values.Select(x => new KeyValuePair<float, float>(x.hp, x.screenPos)); convertHPRatioToScreenPos = new RangeConvertor(hpToPos).Convert; SetFocusTarget(heroCharacter); }
public UIBase AddUI(string path, FSM fsm) { Assert.IsTrue(!string.IsNullOrEmpty(path)); path = path.Trim(); GameObject child = RecycleManager.Instance.Instantiate(path); if (child != null) { Vector3 tempPos = child.transform.position; child.transform.parent = panel.transform; child.transform.localScale = Vector3.one; child.transform.localPosition = tempPos; foreach (var entity in child.GetComponentsInChildren<UIButtonMessage>(true)) { entity.fsm = fsm; } UIBase ret = child.GetComponent<UIBase>(); if (ret == null) { ret = child.AddComponent<UIBase>(); } ret.Init(path, fsm, this); handles.Add(path, ret); return ret; } return null; }
// Use this for initialization public override void Start() { StateMachine = new FSM<EnemyChaserCloneScript> ( this, MoveToPlayer.Instance ); anim = GetComponent<Animator>(); if (!player) AssignPlayer(); WaveSystem.EnemiesRemaining++; // Set initial stats (should overide by applying an upgrade) if (!HasBeenUpgraded) { Health = 1; Velocity = 1; Damage = 1; AttackRate = 5; Experience = 1; } // Movement IsMoving = true; TurnVelocity = 5f; // Attack IsAttacking = false; AttackDistance = 2; NextAttack = AttackRate; //Knockback Force = 50f; mass = 20; //misc renderer.material.color = Color.green; }
public void Inizializza(FSM oggetto) { Cervello = oggetto; agente = Cervello.GetComponent<NavMeshAgent>(); PersonaggioDaInseguire = GameObject.FindGameObjectWithTag("Player"); animatore = Cervello.gameObject.GetComponent<Animator>(); }
public GDGeek.State getState(FSM fsm) { if(state_ == null){ state_ = create(fsm); } return state_; }
void Awake() { _fsm = new FSM<CSTATES>(); AddStates(); AddTransitions(); Instance = this; }
public override PetriNet CreateOutput(FSM.FiniteStateMachine input, ITransformationContext context) { var coloredNet = new ColoredPetriNet(); var defaultColor = new Color(); coloredNet.Colors.Add(defaultColor); context.Bag.DefaultColor = defaultColor; return coloredNet; }
public override void Transform(FSM.State input, Place output, ITransformationContext context) { var colored = output as ColoredPlace; if (colored != null && input.IsStartState) { colored.Tokens.Add(context.Bag.DefaultColor, 1); } }
public MenuAdventure(FSM parentFsm, UIManager2 panel1, UIManager2 panel2) : base(parentFsm, panel1, panel2, "MenuAdventure.fsm") { this.parentFsm = parentFsm; var stages = TableLoader.GetTable<StageEntity2>().Values; this.adventureStages = stages.Where(x => x.gameModeCode == 2); }
void Awake() { originalScale = transform.lossyScale; _fsm = new FSM<CSTATES>(); AddStates(); AddTransitions(); Instance = this; }
public PlayerCharacter(InGameUser user, HeroCharacter heroCharacter, Func<float> getLifeDrainRate, FSM parentFsm) { this.user = user; this.heroCharacter = heroCharacter; this.getLifeDrainRate = getLifeDrainRate; this.parentFsm = parentFsm; heroCharacter.InitFSM("PlayerCharacter.fsm", this, false); }
/// ==================== /// START /// ==================== public virtual void Enter(FSM fsmComp) { // Set FSM if(!fsmComponent) fsmComponent = fsmComp; Init(); }
/// <summary> /// Raises the destroy event. /// </summary> protected virtual void OnDestroy() { if(_fsm != null) { _fsm.Release(); _fsm = null; } }
public MovementStage(FSM fsm) : base(fsm) { // Add Transitions. AddTransition<Idle>(IsIdle); AddTransition<Jump>(() => { return InputManager.JumpHeld; }); AddTransition<UncontrolledFall>(IsNotCollidingBelow); AddTransition<WallRun>(CanWallRun); }
private Transform eTransform; // Transform of this entity #endregion Fields #region Methods /// =================== /// ENTER /// <summary> /// Enters this state /// </summary> /// =================== public override void Enter(FSM fsmComp) { base.Enter(fsmComp); // Obtain transform if (!eTransform) eTransform = this.transform; if (!animator) animator = GetComponent<Animator>(); }
public WallRun(FSM fsm) : base(fsm) { // Add Transitions. AddTransition<MovementStage1>(() => { return Detached() && Momentum < Hero.Stage2MinMomentum; }); AddTransition<MovementStage2>(() => { return Detached() && Momentum < Hero.Stage3MinMomentum; }); AddTransition<Jump>(() => { return InputManager.JumpHeld; }); AddTransition<UncontrolledFall>(() => { return InputManager.Grip == 0.0f; }); }
/// <summary> /// Supports serialization. /// </summary> public Brain() { FSM = new FSM<BrainState>( delegate(BrainState a) { if (Self.Stats.HealthPercent < 10) return BrainState.Flee; return BrainState.Patrol; }); }
public MovementStage3(FSM fsm) : base(fsm) { // Add Transitions. AddTransition<MovementStage2>(() => { return Momentum < Hero.Stage3MinMomentum; }); this.maxAnimationSpeed = 2.0f; this.maxSpeed = Hero.Stage3MaxSpeed; this.rotationRate = 2.0f; }
public StageObject(ObjectField objectField, ObjectStage objectStage, ItemDropManager itemDropManager, FSM parentFsm) : base(objectStage.OverlapEvent, objectField, true) { Assert.IsTrue(objectStage != null); this.objectStage = objectStage; this.itemDropManager = itemDropManager; this.parentFsm = parentFsm; label = string.Format("{0}\n{1}", objectStage.Type.ToString(), objectStage.ObjectID); }
private static void PlayIncremental(long[, ,] times, int sizeIdx, int iteration, Stopwatch watch, FSM.FiniteStateMachine incMachine, List<FSMWorkloadAction> workload) { watch.Restart(); foreach (var item in workload) { item.Perform(incMachine); } watch.Stop(); times[sizeIdx, iteration, 5] = watch.ElapsedTicks; }
public override void Update(FSM fsm, FSMActor owner) { base.Enter(fsm, owner); //Wait for Block Down //Change State //owner.ChangeState((int)GameSystemState_ID.JudgeEliminate); //Test FSM_GameSystem curFsm = fsm as FSM_GameSystem; if (curFsm._testTimer > 0) { curFsm._testTimer -= Time.deltaTime; } if (curFsm._testTimer < 0) { curFsm._testTimer = 0.0f; owner.ChangeState((int)GameSystemState_ID.SpawnNewBlock); } }
internal static void AddTransitions(FSM fsm, int state, CodeStatementCollection stmts, Set <int> visited) { if (visited.Contains(state)) { return; } else { visited.Add(state); } Transitions currTrans = null; fsm.Trans.TryGetValue(state, out currTrans); if (currTrans == null || currTrans.Count == 0) { return; } CreateAddTransitionStmts(fsm, stmts, state, currTrans, visited); }
public override bool ExecuteState(FSM fsm) { if (!isInit) { FSM = fsm as PlayerFSM; currentUnit = FSM.GetOwner().CurrentSelectedUnit; enemyCurrentUnit = currentUnit.CurrentEnemy; isInit = OnStartState(); } if (OnExecuteState() || ForceQuit) { FSM.GetOwner().CurrentSelectedUnit.CurrentEnemy = null; FSM.GetOwner().CurrentSelectedUnit = null; FSM.ChangeState(PlayerFSM.PlayerStates.IDLE); return(OnEndState()); } return(false); }
public override bool ExecuteState(FSM fsm) { if (!isInit) { fSM = fsm as UnitFSM; unit = ((UnitFSM)fsm).GetUnitOwner(); isInit = OnStartState(); } path = unit.CurrentPath; if (path != null) { if (OnExecuteState() == true) { return(OnEndState()); } } return(false); }
// Start is called before the first frame update void Start() { rigid = GetComponent <Rigidbody>(); target = GameObject.FindGameObjectWithTag("Player").transform; navMeshAgent = GetComponent <NavMeshAgent>(); fsm = new FSM(gameObject, this); RanaEstadoSalto estadoSalto = new RanaEstadoSalto(this); IdleRana estadoIdle = new IdleRana(this); EnemigoDesvanecidoEstado estadoDesvanecido = new EnemigoDesvanecidoEstado(this); EnemigoAturdidoEstado estadoAturdido = new EnemigoAturdidoEstado(this); fsm.AddState(EstadosRana.Salto, estadoSalto); fsm.AddState(EstadosRana.IdleRana, estadoIdle); fsm.AddState(EstadosEnemigo.Aturdido, estadoAturdido); fsm.AddState(EstadosEnemigo.Desvanecido, estadoDesvanecido); Inicializar(); }
public void Update() { foreach (GameObject g in FSMList) { FSM f = g.GetComponent <FSM>(); if (f.priority == Utils.priority.low) //update once per second { if (elapsedTime >= 1.0f) { elapsedTime = 0.0f; f.updateFSM(); } } else // update every frame { f.updateFSM(); } } elapsedTime += Time.deltaTime; }
/// <summary> 终止计划(在<see cref="interval"/>之后才会重新搜寻计划) </summary> public void AbortPlan() { if (HasPlan) { actionQueue.Clear(); } if (CurrentAction != null) { CurrentAction.OnPostPerform(false); // 如果动作执行失败,转换到空闲状态,并通知因为该动作导致计划失败 if (Provider != null) { Provider.PlanAborted(CurrentAction); } } CurrentAction = null; CurrentGoal = null; FSM.ChangeTo("IdleState"); }
private void Init() { characterFSM = new FSM(); idleState = new IdleState(); walkState = new WalkState(); characterFSM.AddState(idleState, gameObject); characterFSM.AddState(walkState, gameObject); Transition idle2walk = new Transition(idleState, walkState); idle2walk.transition += idle2WalfTransition; characterFSM.AddTransition(idle2walk); Transition walk2Idle = new Transition(walkState, idleState); walk2Idle.transition += walk2IdleTransition; characterFSM.AddTransition(walk2Idle); characterFSM.Init(); }
void Start() { FSMCondition bt = BlueTime; FSMCondition rt = RedTime; FSMTransition t1 = new FSMTransition(bt); FSMTransition t2 = new FSMTransition(rt); FSMState Red = new FSMState(); Red.enterActions.Add(GoRed); FSMState Blue = new FSMState(); Blue.enterActions.Add(GoBlue); Blue.AddTransition(t2, Red); Red.AddTransition(t1, Blue); fsm = new FSM(Red); }
/// <summary> /// 重新开始游戏 /// </summary> public void ReStartGame() { _currentTurnCount = 0; _currentPoints = 0; _currentPlayerIndex = 0; for (var i = 0; i < _players.Length; i++) { var tmpPlayer = _players[i]; if (null != tmpPlayer) { tmpPlayer.ReStartGame(); } } if (null != _fsm) { _fsm.Stop(); _fsm = null; } }
// Start is called before the first frame update void Start() { fsm = new FSM("Test Ai"); testState1 = fsm.AddState("testState1"); testState2 = fsm.AddState("testState2"); testState3 = fsm.AddState("testState3"); testAction1 = new TestAction1(testState1); testAction2 = new TestAction1(testState2); testAction3 = new TestAction1(testState3); finishEvent1 = new List <string> { "To 2", "To 3" }; finishEvent2 = new List <string> { "To 1", }; finishEvent3 = new List <string> { "To 1", }; testState1.AddAction(testAction1); testState2.AddAction(testAction2); testState3.AddAction(testAction3); testState1.AddTransition("To 2", testState2); testState1.AddTransition("To 3", testState3); testState2.AddTransition("To 1", testState1); testState3.AddTransition("To 1", testState1); testAction1.init("test 1", 1f, finishEvent1); testAction2.init("test 2", 1f, finishEvent2); testAction3.init("test 3", 1f, finishEvent3); fsm.Start("testState1"); }
public void Inizializza(FSM oggetto) { MioCervello = oggetto; Agente = MioCervello.gameObject.GetComponent <NavMeshAgent>(); Animatore = MioCervello.gameObject.GetComponent <Animator>(); if (MioCervello.classeGoblin == 1) { Destinazioni = new Transform[GameObject.Find("GeneraPercorso").GetComponent <GeneraPercorso>().Itinerario(TipoPercorso.A).Length]; for (int i = 0; i < Destinazioni.Length; i++) { Destinazioni[i] = GameObject.Find("GeneraPercorso").GetComponent <GeneraPercorso>().Itinerario(TipoPercorso.A)[i]; } } else if (MioCervello.classeGoblin == 2) { Destinazioni = new Transform[GameObject.Find("GeneraPercoso").GetComponent <GeneraPercorso>().Itinerario(TipoPercorso.B).Length]; for (int i = 0; i < Destinazioni.Length; i++) { Destinazioni[i] = GameObject.Find("GeneraPercorso").GetComponent <GeneraPercorso>().Itinerario(TipoPercorso.B)[i]; } } else if (MioCervello.classeGoblin == 3) { Destinazioni = new Transform[GameObject.Find("GeneraPercorso").GetComponent <GeneraPercorso>().Itinerario (TipoPercorso.C).Length]; for (int i = 0; i < Destinazioni.Length; i++) { Destinazioni[i] = GameObject.Find("GeneraPercorso").GetComponent <GeneraPercorso> ().Itinerario(TipoPercorso.C)[i]; } } ProssimaDirezione = Destinazioni[indiceDestinazioni]; Agente.SetDestination(ProssimaDirezione.position); }
private void Awake() { nodoFinalObstaculo = false; nodoInicialObstaculo = false; statePath = StatePath.Nulo; Depositos = new List <GameObject>(); if (GameManager.instanceGameManager != null) { gm = GameManager.instanceGameManager; } // Aca defino las relaciones de estado y le hago el new al objeto FSM fsm = new FSM((int)EstadosAldeano.Count, (int)EventosAldeano.Count, (int)EstadosAldeano.Idle); //minero fsm.SetRelations((int)EstadosAldeano.Idle, (int)EstadosAldeano.IrAMinar, (int)EventosAldeano.ClickInMine); fsm.SetRelations((int)EstadosAldeano.IrAMinar, (int)EstadosAldeano.Minando, (int)EventosAldeano.CollisionMine); fsm.SetRelations((int)EstadosAldeano.IrAMinar, (int)EstadosAldeano.CancelarAccion, (int)EventosAldeano.Stop); fsm.SetRelations((int)EstadosAldeano.Minando, (int)EstadosAldeano.LLevarOro, (int)EventosAldeano.FullCapasity); fsm.SetRelations((int)EstadosAldeano.Minando, (int)EstadosAldeano.IrAMinar, (int)EventosAldeano.ClickInMine); fsm.SetRelations((int)EstadosAldeano.Minando, (int)EstadosAldeano.CancelarAccion, (int)EventosAldeano.Stop); fsm.SetRelations((int)EstadosAldeano.LLevarOro, (int)EstadosAldeano.DepositarOro, (int)EventosAldeano.CollisionHouse); fsm.SetRelations((int)EstadosAldeano.LLevarOro, (int)EstadosAldeano.CancelarAccion, (int)EventosAldeano.Stop); fsm.SetRelations((int)EstadosAldeano.DepositarOro, (int)EstadosAldeano.Idle, (int)EventosAldeano.Stop); fsm.SetRelations((int)EstadosAldeano.DepositarOro, (int)EstadosAldeano.IrAMinar, (int)EventosAldeano.ClickInMine); fsm.SetRelations((int)EstadosAldeano.CancelarAccion, (int)EstadosAldeano.Idle, (int)EventosAldeano.Stop); fsm.SetRelations((int)EstadosAldeano.Idle, (int)EstadosAldeano.LLevarOro, (int)EventosAldeano.ClickInHouse); fsm.SetRelations((int)EstadosAldeano.IrAMinar, (int)EstadosAldeano.LLevarOro, (int)EventosAldeano.ClickInHouse); fsm.SetRelations((int)EstadosAldeano.Minando, (int)EstadosAldeano.LLevarOro, (int)EventosAldeano.ClickInHouse); //movimiento fsm.SetRelations((int)EstadosAldeano.Idle, (int)EstadosAldeano.MoverAldeano, (int)EventosAldeano.ClickInMap); fsm.SetRelations((int)EstadosAldeano.IrAMinar, (int)EstadosAldeano.MoverAldeano, (int)EventosAldeano.ClickInMap); fsm.SetRelations((int)EstadosAldeano.Minando, (int)EstadosAldeano.MoverAldeano, (int)EventosAldeano.ClickInMap); fsm.SetRelations((int)EstadosAldeano.MoverAldeano, (int)EstadosAldeano.Idle, (int)EventosAldeano.Stop); fsm.SetRelations((int)EstadosAldeano.MoverAldeano, (int)EstadosAldeano.LLevarOro, (int)EventosAldeano.ClickInHouse); fsm.SetRelations((int)EstadosAldeano.MoverAldeano, (int)EstadosAldeano.IrAMinar, (int)EventosAldeano.ClickInMine); normalSpeed = speed; waterSpeed = normalSpeed / 2; }
private void Start() { _spawner = FindObjectOfType <EnemySpawner>(); enemyTotal = _spawner.EnemyTotal; sceneChangeEffect = Camera.main.GetComponent <ISceneChangeEffect>(); _fsm = new FSM <GameStateType>(this); _fsm.AddState(new GameInit(_fsm)); _fsm.AddState(new GameRunning(_fsm)); _fsm.AddState(new GamePaused(_fsm)); _fsm.AddState(new GameFailure(_fsm)); _fsm.AddState(new GameSucceed(_fsm)); UIManager.Instance.GetWindow(UIWindowID.GamePaused).transform.FindChildComponentByName <Button>("Btn_Back") .onClick.AddListener( () => { _fsm.ChangeState(GameStateType.GameRunning); }); if (sceneChangeEffect != null) { sceneChangeEffect.Run(false, () => { if (onFadeInSceneComplete != null) { onFadeInSceneComplete(); } }); } else { if (onFadeInSceneComplete != null) { onFadeInSceneComplete(); } } }
void Start() { fsm = GetComponent <FSM>(); spriteRenderer = GetComponent <SpriteRenderer>(); spriteRenderer.enabled = false; spriteRenderer.color = Color.grey; fsm.states = new List <State>(); fsm.states.Add(new State("Play")); fsm.states.Add(new State("Hold")); fsm.states.Add(new State("Rewinding")); fsm.states.Add(new State("Rerewinding")); fsm.currentState = fsm.states[0]; fsm.transitions = new List <Transition>(); fsm.transitions.Add(new Transition("Play", "Hold", Play_Hold)); fsm.transitions.Add(new Transition("Hold", "Play", Hold_PLay)); fsm.transitions.Add(new Transition("Hold", "Rewinding", Hold_Rewinding)); fsm.transitions.Add(new Transition("Rewinding", "Hold", Rewinding_Hold)); fsm.transitions.Add(new Transition("Hold", "Rerewinding", Hold_Rerewinding)); fsm.transitions.Add(new Transition("Rerewinding", "Hold", Rerewinding_Hold)); for (int i = 0; i < fsm.states.Count; i++) { if (fsm.states[i].name == "Play") { fsm.states[i].OnEnter = OnEnterPlay; fsm.states[i].OnStay = OnStayPlay; fsm.states[i].OnExit = OnExitPlay; } else if (fsm.states[i].name == "Rewinding") { fsm.states[i].OnStay = OnStayRewinding; } else if (fsm.states[i].name == "Rerewinding") { fsm.states[i].OnStay = OnStayRerewinding; } } }
/// <summary> /// Get all states in the given finite automaton from which no accepting state is reachable. /// </summary> /// <param name="fa">given finite automaton</param> /// <returns>all dead states in the finite automaton</returns> public static Set <Term> GetDeadStates(FSM fa) { //build a graph from fa Dictionary <Term, int> stateToVertexMap = new Dictionary <Term, int>(); stateToVertexMap[fa.InitialState] = 0; int i = 1; foreach (Term state in fa.States.Remove(fa.InitialState)) { stateToVertexMap[state] = i++; } //create edges that correspond to the transitions GraphTraversals.Edge[] edges = new GraphTraversals.Edge[fa.Transitions.Count]; Triple <Term, CompoundTerm, Term>[] transitions = new Triple <Term, CompoundTerm, Term> [fa.Transitions.Count]; i = 0; foreach (Triple <Term, CompoundTerm, Term> trans in fa.Transitions) { edges[i] = new GraphTraversals.Edge(stateToVertexMap[trans.First], stateToVertexMap[trans.Third], i); transitions[i++] = trans; } GraphTraversals.Graph g = new GraphTraversals.Graph(0, edges, new GraphTraversals.Edge[] { }, GraphTraversals.WeakClosureEnum.DoNotClose); int[] acceptingVertices = new int[fa.AcceptingStates.Count]; i = 0; foreach (Term accState in fa.AcceptingStates) { acceptingVertices[i++] = stateToVertexMap[accState]; } GraphTraversals.HSet deadVertices = g.DeadStates(acceptingVertices); return(fa.States.Select(delegate(Term state) { return deadVertices.Contains(stateToVertexMap[state]); })); }
public static FSM ProjectFromProduct(FSM finiteAutomaton, Set <Symbol> projectedSymbols, Sequence <Branch> treePosition, Dictionary <Term, IState> /*?*/ stateMap, out Dictionary <Term, IState> /*?*/ reductStateMap) { Set <IState> projectedIStates = finiteAutomaton.States.Convert <IState>(delegate(Term t) { return(GetReduct(treePosition, stateMap[t])); }); Set <IState> projectedAcceptingIStates = finiteAutomaton.AcceptingStates.Convert <IState>(delegate(Term t) { return(GetReduct(treePosition, stateMap[t])); }); reductStateMap = new Dictionary <Term, IState>(); Dictionary <IState, Term> reverseMap = new Dictionary <IState, Term>(); Term initialState = new Literal(0); IState initialStateReduct = GetReduct(treePosition, stateMap[finiteAutomaton.InitialState]); reductStateMap[initialState] = initialStateReduct; reverseMap[initialStateReduct] = initialState; int i = 1; foreach (IState s in projectedIStates.Remove(initialStateReduct)) { Term t = new Literal(i++); reductStateMap[t] = s; reverseMap[s] = t; } Set <Term> states = new Set <Term>(reductStateMap.Keys); Set <Term> acceptingStates = projectedAcceptingIStates.Convert <Term>(delegate(IState x){ return(reverseMap[x]); }); Set <Triple <Term, CompoundTerm, Term> > transitions = finiteAutomaton.Transitions.Convert <Triple <Term, CompoundTerm, Term> >( delegate(Triple <Term, CompoundTerm, Term> t) { return(new Triple <Term, CompoundTerm, Term>(reverseMap[GetReduct(treePosition, stateMap[t.First])], t.Second, reverseMap[GetReduct(treePosition, stateMap[t.Third])])); }); Set <Triple <Term, CompoundTerm, Term> > transitions1 = transitions.Select(delegate(Triple <Term, CompoundTerm, Term> t) { return(projectedSymbols.Contains(t.Second.Symbol)); }); return(new FSM(initialState, states, transitions1, acceptingStates, projectedSymbols)); }
/// <summary> /// This is called after death or when set to sleep, /// Use this to reset states. The base will reset stats and telemetry /// </summary> protected virtual void Restart() { //reset physics SetPhysicsActive(true, false); if (animator) { animator.Stop(); } if (visibleGO) { visibleGO.SetActive(true); } //reset blink Blink(0.0f); mStats.Reset(); mStats.isInvul = true; if (FSM) { FSM.Reset(); } if (mBodyCtrl) { mBodyCtrl.enabled = true; } Jump(0.0f); if (stunGO) { stunGO.SetActive(false); } StopCoroutine(DoRespawnWaitDelayKey); }
void OnGUI() { EditorGUILayout.LabelField("FSM Object:", EditorStyles.boldLabel); go = (GameObject)EditorGUILayout.ObjectField(go, typeof(GameObject), true); if (go != null) { fsm = go.GetComponent <FSM>(); //fSM.GetState(); fsm.name = EditorGUILayout.TextField("Name:", fsm.name); EditorGUILayout.LabelField("States:", EditorStyles.boldLabel); states = fsm.GetStateList(); Debug.Log("State #: " + states.Count); foreach (State s in states) { s.Name = EditorGUILayout.TextField("State Name:", s.Name); } //actionGo = (GameObject)EditorGUILayout.ObjectField("Action GO:", actionGo, typeof(GameObject), true); EditorGUILayout.LabelField("New Transition:", EditorStyles.boldLabel); conditionName = EditorGUILayout.TextField("Condition Name:", conditionName); condition = EditorGUILayout.TextField("Condition:", condition); nextState = EditorGUILayout.TextField("Next State:", nextState); /* if (GUILayout.Button("Add Transition")) * { * tempTransition.Add(new Transition(new Condition(conditionName, condition), new State(nextState))); * transitionsAdded = true; * Debug.Log("Trying to repaint"); * } * EditorGUILayout.Space(); * if(transitionsAdded) { * EditorGUILayout.LabelField ("Transitions:", EditorStyles.boldLabel); * foreach(Transition t in tempTransition) * { * EditorGUILayout.LabelField (t.ToString()); * } * }*/ } }
private void Start() { playerFSM = new FSM(); var idle = new PlayerIdle(E_FSM_State_Type.PlayerIdle, this); var victory = new PlayerVictory(E_FSM_State_Type.PlayerVictory, this); var jump = new PlayerJump(E_FSM_State_Type.PlayerJump, this); var look = new PlayerLook(E_FSM_State_Type.PlayerLook, this); var defeat = new PlayerDefeat(E_FSM_State_Type.PlayerDefeat, this); var Dead = new PlayerDead(E_FSM_State_Type.PlayerDead, this); playerFSM.RegistState(idle); playerFSM.RegistState(victory); playerFSM.RegistState(jump); playerFSM.RegistState(look); playerFSM.RegistState(defeat); playerFSM.RegistState(Dead); playerFSM.Go(idle); FW.MonoMgr.Instance.AddUpdateListener(playerControl.Updates); }
private void Awake() { gameFSM = new FSM <GameManager>(this); if (!GetComponent <CornItemManager>()) { gameObject.AddComponent <CornItemManager>(); } _cornItemManager = GetComponent <CornItemManager>(); _FoodInteractionScript = FindObjectOfType <CornItemInteractions>(); _monologueManager = GetComponent <CornMonologueManager>(); _audioManager = FindObjectOfType <AudioManager>(); _mouseLook = FindObjectOfType <CornMouseLook>(); TitleMenu.SetActive(false); OrderMenu = GameObject.Find("OrderMenu"); OrderMenu.SetActive(false); FindObjectOfType <CornBuoyancy>().waterBoilTimeInseconds = waterBoilSeconds; textAnimFSM = GetComponent <PlayMakerFSM>(); cleanupBowl = GameObject.Find("BowlForTmr"); backgroundMusic = GameObject.Find("BackgroundMusic").GetComponent <AudioSource>(); // if (Debug_StartWithState == 1 || Debug_StartWithState == 2) // { // foreach (var child in FindObjectsOfType<FoodSpawner>()) // { // child.StartCoroutine(child.Initiate()); // } // // gameFSM.TransitionTo<CookingState>(); // } // else if(Debug_StartWithState == 0) // { // gameFSM.TransitionTo<OrderState>(); //default state // } }
public void AddSubstate(string name, FSM <T> subStateMachine, StateEvent enter, StateEvent update = null, StateEvent exit = null) { subStateMachine.DataObj = DataObj; SubState newState = new SubState() { Name = name, SubStateMachine = subStateMachine, SubEnter = enter, SubUpdate = update, SubExit = exit }; int index = AllStates.BinarySearch(newState, StaticStateNameComparer); if (index < 0) { AllStates.Insert(~index, newState); if (NextState == null) { NextState = newState; } } else { Debug.LogWarning("State " + name + " already exist and cannot be added."); } }
void FindNewPosition_Update() { _findPositionTimeout -= Time.deltaTime; if (_findPositionTimeout > 0) { return; } _newWanderPosition = _currentBotWanderComponent.GetNewWanderPosition(WanderCenter); if (_newWanderPosition != null) { BotLocomotiveComponent.FocusOnPosition(_newWanderPosition.Value); FSM.ChangeState(FStatesWander.MovingToPosition); } else { LogInDebugMode("_newWanderPosition != null"); _wanderAutoRetry = false; FSM.ChangeState(FStatesWander.CannotWander); } }
void Start() { if (actionContainer == null) { Debug.LogError("GOAP Agent named " + gameObject.name + " doesn't have an action container. The agent will disable itself."); enabled = false; return; } mStateMachine = new FSM(this); mAvailableActions = new HashSet <Action>(); mPlan = new Plan(); mPlanner = new Planner(); LoadActorFromComponent(); LoadActionsFromContainer(); CreateIdleState(); CreateMovingState(); CreatePerformState(); mStateMachine.PushState(mIdleState); }
private void MoveToState(FSM fsm) { // Move the game object. var action = currentActions.Peek() as GoapAction.WithContext; if (action.actionData.RequiresInRange() && action.target == null) { Debug.Log("<color=red>Fatal error:</color> Action requires a target but has none. Planning failed. You did not assign the target in your Action.checkProceduralPrecondition()"); // Move. fsm.PopState(); // Perform. fsm.PopState(); fsm.PushState(IdleState); return; } // Get the agent to move itself. if (MoveAgent(action)) { fsm.PopState(); } }
public void Initialize(Supervisor sup, List <FSM.Event> previousEvents, string customInit = null) { // Set central controller centralController = manager.GetComponent <CentralController>(); // Instantiate supervisor //supervisorio = new FSM(automaton); supervisorio = new FSM(sup, customInit); // Get initial gridosition - normally (0,0) position = supervisorio.currentState.GetPosition(); // Instantiate Handlers animationComponent.Initialize(manager); interfaceComponent.Initialize(manager); communicationComponent.Initialize(manager); // Set initial position animationComponent.FixPosition(); supervisorio.RunEvents(previousEvents); }
void ChangeState(FSM state) { switch (state) { case FSM.Fence: animator.SetInteger("State", 0); //animator.Play ("FenceIdle"); break; case FSM.Stab: stabTime = Time.time; break; case FSM.Run: animator.SetInteger("State", 1); //animator.Play ("Run"); break; case FSM.Jump: rbody.AddForce(jumpForce * Vector3.up); break; case FSM.Dead: isDead = true; rbody.velocity = Vector3.zero; deathTime = Time.time; capsule.enabled = false; meshRender.enabled = false; swordChecker.active = false; StartCoroutine(DelayVoidFunction(1, DropSword)); gameController.SendMessage("PlayerIsAlive", new PlayerAlive(playerid, false)); break; default: break; } playerState = state; }
// Use this for initialization void Start() { anim = GetComponent <Animator>(); playerTags.Add("Bean"); playerTags.Add("Eal"); playerTags.Add("Loin"); playerTags.Add("Sage"); FSMState waiting = new FSMState(); waiting.enterActions.Add(StopCounting); FSMState angry = new FSMState(); angry.enterActions.Add(StartCounting); angry.stayActions.Add(UpdateCounter); FSMState hit = new FSMState(); hit.enterActions.Add(Hit); FSMState end = new FSMState(); end.enterActions.Add(ToSecondStage); FSMTransition t1 = new FSMTransition(PlayersInRange); FSMTransition t2 = new FSMTransition(NoPlayersInRange); FSMTransition t3 = new FSMTransition(TimeOver); FSMTransition t4 = new FSMTransition(EnoughPlayersInRange); waiting.AddTransition(t1, angry); angry.AddTransition(t2, waiting); angry.AddTransition(t3, hit); angry.AddTransition(t4, end); hit.AddTransition(t2, waiting); fsm = new FSM(waiting); }
public XmasLogBehaviour4(Boss boss) : base(boss) { // State machine _stateMachine = new FSM <BehaviourState>("xmas-log-behaviour4"); var targetingInitialPositionBehaviour = new FSMBehaviour <BehaviourState>(BehaviourState.TargetingInitialPosition) .OnUpdate(TargetingInitialPositionTaskUpdate); var removingHollyBehaviour = new FSMBehaviour <BehaviourState>(BehaviourState.HollyAttack) .OnEnter(RemovingHollyTaskEnter); var hollyAttackBehaviour = new FSMBehaviour <BehaviourState>(BehaviourState.HollyAttack) .OnEnter(HollyAttackTaskEnter) .OnUpdate(HollyAttackTaskUpdate); _stateMachine.Add(BehaviourState.TargetingInitialPosition, targetingInitialPositionBehaviour); _stateMachine.Add(BehaviourState.RemovingHolly, removingHollyBehaviour); _stateMachine.Add(BehaviourState.HollyAttack, hollyAttackBehaviour); }
void Start() { turret = GetComponent <TurretBehaviour>(); viewFromGround = new Vector3(transform.position.x, 0f, transform.position.z); //for overlap spheres //States FSMState idle = new FSMState(); idle.enterActions.Add(Wait); FSMState active = new FSMState(); active.enterActions.Add(Alerted); active.exitActions.Add(StopAlert); FSMState attack = new FSMState(); attack.enterActions.Add(StartAttack); attack.stayActions.Add(Attack); attack.exitActions.Add(StopAttack); //Transitions FSMTransition t1 = new FSMTransition(PatrolInCamp); FSMTransition t2 = new FSMTransition(NobodyOnAlarm); FSMTransition t3 = new FSMTransition(EnemiesInRange); FSMTransition t4 = new FSMTransition(NoEnemiesInRange); // Link states with transitions idle.AddTransition(t1, active); active.AddTransition(t2, idle); active.AddTransition(t3, attack); attack.AddTransition(t4, active); //Setup a FSA at initial state fsm = new FSM(idle); // Start monitoring StartCoroutine(Patrol()); }