void Awake() { controllerCamera = Camera.mainCamera; //Setup Messenger Messenger.AddListener(InputManager.kMegatileCapMet, OnOpenMenu); Messenger<Vector3>.AddListener(InputManager.kRightClickedTile, OnCloseMenu); Messenger.AddListener(kClose, OnCloseMenu); //Setup GUIGroup menuGroup = new GUIContainer(controllerCamera.pixelRect,false); menuGroup.anchor.Set(GUIAnchor.BottomCenter); GameGUIManager.AddGUIObject(menuGroup); //Setup Transitions and State Machine Transition<TileSelectionMenu> goToOptions = new Transition<TileSelectionMenu>(this, states["Options"]); Transition<TileSelectionMenu> closeMenu = new Transition<TileSelectionMenu>(this, states["Waiting"]); states["Waiting"].AddTransition(goToOptions); states["Options"].AddTransition(closeMenu); goToOptions.InitFromExpression ( "{ TransitionBehavior_OnEvent openMenu( OpenMenu ); } openMenu"); closeMenu.InitFromExpression ( "{ TransitionBehavior_OnEvent closeMenu( CloseMenu ); } closeMenu"); behaviour.ChangeState( states["Waiting"], this ); }
public void DeleteTransition(Transition transition) { if (map.ContainsKey(transition)) { map.Remove(transition); } }
public TransitionController(string visualiser, Transition transition) { _priState = null; _subState = null; _transition = transition; _visualiser = visualiser; }
public void AddTransition(Transition t) { if (t != null) { _transitions.Add(t); } }
public static StateModel ToCommon(IList<StateControl> stateControls, int modelId, string modelName) { var sm = new StateModel(); sm.States = new List<State>(); sm.Transitions = new List<Transition>(); int i = 0; foreach (var control in stateControls) { var state = new State(); state.Default = control.StartState; state.Name = control.DisplayName; state.StateID = i; Point position = Page1.GetPosition(control); state.X = (int) position.X; state.Y = (int) position.Y; control.StateId = i; i++; sm.States.Add(state); } foreach (var control in stateControls) { foreach (var arrow in control.ArrowsOut) { var trans = new Transition(); trans.DestinationStateRef = arrow.HeadControl.StateId; trans.SourceStateRef = arrow.TailControl.StateId; sm.Transitions.Add(trans); } } sm.ModelID = modelId; sm.ModelName = modelName; return sm; }
public void AddTransition(Transition trans, StateID id) { //first step of the fsm //check the args and see if they are invalid if (trans == Transition.NullTransition) { Debug.LogError("FSM had a pretty bad error. Null transition is not allowed for a real tranisition. \n You have a shit ton of work david"); return; } if (id == StateID.NullStateID) { Debug.LogError("FSM had a pretty bad error. Null STATE id is not allowed for a real ID"); return; } // deterministic FSM // check if current transition was already inside the map if (map.ContainsKey(trans)) { // f**k, if this hits ive hit a transition that already has a transition // Enum enumerations = RuntimeTypeHandle.ReferenceEquals(StateID); Debug.LogError("FSM had a pretty bad error" + stateID.ToString() + " Already has a transition" +trans.ToString() + " Impossible to assign to another state"); return; } map.Add(trans, id); }
protected Effect(Control control, int milliseconds) { Manager.Instance.IncludeResourceScript("Effects.js"); _control = control; _milliseconds = milliseconds; _type = Transition.Explosive; }
public void CompositeStateTest() { var sm = new StateMachine(); var s0 = CreateState("0"); var s0States = new StateCollection(); s0.ParallelSubStates.Add(s0States); sm.States.Add(s0); var s00 = CreateState("00"); s0States.Add(s00); var s01 = CreateState("01"); s0States.Add(s01); var t0 = new Transition { SourceState = s0, TargetState = s0, }; t0.Action += (s, e) => _events = _events + "A0"; sm.Update(TimeSpan.FromSeconds(1)); sm.Update(TimeSpan.FromSeconds(1)); t0.Fire(); sm.Update(TimeSpan.FromSeconds(1)); sm.Update(TimeSpan.FromSeconds(1)); Assert.AreEqual("E0E00U00U0U00U0X00X0A0E0E00U00U0U00U0", _events); }
/// <summary> /// Hide menu /// </summary> public virtual void hideMenu(float transitionTimer, MenuTransition path = MenuTransition.BACKWARD, Callback callback = null) { // Stop any transition that's currently in effect TransitionHandler.removeTransition(alphaTransition); TransitionHandler.removeTransition(positionTransition); if(transitionTimer == 0.0f) { // Make UI object invisible imgAlpha.alpha = 0.0f; // Turn off the UI game object gameObject.SetActive(false); if(callback != null) { callback(); } } else { // Animate the position transition positionTransition = TransitionHandler.addTransition(() => Vector2.zero, x => menuTransform.anchoredPosition = x, new Vector2(0, -30), transitionTimer).toggleTimeScale(false); // Fade out the menu then disable the object after it's finished fading out alphaTransition = TransitionHandler.addTransition(()=>getAlpha.alpha, x => getAlpha.alpha = x, 0.0f, transitionTimer).toggleTimeScale(false).finishLerp(() => { gameObject.SetActive(false); if (callback != null) { callback(); } }); } }
// Add Transition public void AddTransition(Transition trans, StateID id) { //check if transition exist if(trans == Transition.NULL) { Debug.LogError("Trying to add a null transition"); return; } if(id == StateID.NULL) { Debug.LogError("Trying to add a null state"); return; } if(trans == Transition.E_NOHP) { Debug.Log("trans: " + trans.ToString() + " StateID: " + id.ToString()); } // check if current map already contains key if(map.ContainsKey(trans)) { Debug.LogError(trans.ToString() + " transition Exist, unable to have duplicate transitions for State: " + id.ToString()); return; } map.Add(trans, id); Debug.Log("Sucessfully added: " + trans.ToString() + " id extract: " + map[trans] + " Current StateID: " + STATE_ID.ToString()); }
public static FiniteStateMachine GenerateStateMachine(string id, int states, double transitionsPerState, double endStateProbability) { var fsm = new FiniteStateMachine(); var rand = new Random(); fsm.Id = id; for (int i = 0; i < states; i++) { var state = new State(); state.Name = "q" + i.ToString(); state.IsEndState = rand.NextDouble() < endStateProbability; fsm.States.Add(state); } var transitions = (int)Math.Floor(states * transitionsPerState + 0.5); for (int i = 0; i < transitions; i++) { State start; State end; string input; do { start = fsm.States[rand.Next(fsm.States.Count)]; end = fsm.States[rand.Next(fsm.States.Count)]; input = __inputs[rand.Next(__inputs.Length)]; } while (start.Transitions.Any(t => t.Input == input)); var transition = new Transition(); transition.StartState = start; transition.EndState = end; transition.Input = input; fsm.Transitions.Add(transition); } return fsm; }
public void addTransition(Transition transition,string eventName) { if (!transitionList.ContainsKey(eventName)) transitionList.Add(eventName, transition); else Debug.Log("Transition "+eventName+" not Added. Already in "+name+"'s transitions."); }
public void AddTransition(Transition trans, StateID id) { // Check if anyone of the args is invalid if (trans == Transition.NullTransition) { Debug.LogError("FSMState ERROR: NullTransition is not allowed for a real transition"); return; } if (id == StateID.NullStateID) { Debug.LogError("FSMState ERROR: NullStateID is not allowed for a real ID"); return; } // Since this is a Deterministic FSM, // check if the current transition was already inside the map if (map.ContainsKey(trans)) { Debug.LogError("FSMState ERROR: State " + stateID.ToString() + " already has transition " + trans.ToString() + "Impossible to assign to another state"); return; } map.Add(trans, id); }
public void Transition_AllowsNullSource() { var t = new Transition<StubStateModel>( new Trigger("trigger"), null, new Mock<State<StubStateModel>>("to").Object); }
/// <summary> /// Constructs a button. /// </summary> /// <param name="text"></param> /// <param name="position"></param> /// <param name="transitionOnTime"></param> /// <param name="transitionOffTime"></param> /// <param name="transitionOnSide"></param> /// <param name="transitionOffSide"></param> public Button( string text, Vector2 position, Color color, Color selectedColor, float scale, float selectedScale, double selectionTransitionOnTime, double selectionTransitionOffTime, double transitionOnTime, double transitionOffTime, ScreenSide transitionOnSide, ScreenSide transitionOffSide) : base(transitionOnTime, transitionOffTime, transitionOnSide, transitionOffSide, null, position) { this.text = new TextComponent(text, position); this.color = color; this.selectedColor = selectedColor; this.scale = scale; this.selectedScale = selectedScale; this.selectionTransition = new Transition(selectionTransitionOnTime, selectionTransitionOffTime); this.OnSelection += Button_Selection; this.OnDeselection += Button_Deselection; this.TabStop = true; }
public void Transition_Equals_CustomGuardSame_SameProps_ReturnsTrue() { Func<StubStateModel, bool> guard = m => true; var t1 = new Transition<StubStateModel>(new Trigger("t1"), new State<StubStateModel>("s1"), new State<StubStateModel>("s2"), guard); var t2 = new Transition<StubStateModel>(new Trigger("t1"), new State<StubStateModel>("s1"), new State<StubStateModel>("s2"), guard); Assert.True(t1.Equals(t2)); }
/** <summary>Creates a new action within the given document context.</summary> */ public DoTransition( Document context, Transition transition ) : base(context, PdfName.Trans) { Transition = transition; }
public void AddTransition(Transition transition, FSMStateID id) { if (map.ContainsKey(transition)) { return; } map.Add(transition, id); }
public void PreviousOrSame_LastYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.PreviousOrSame(Instant.FromUtc(1971, 1, 1, 0, 0) - Duration.Epsilon, Offset.Zero, Offset.Zero); Transition? expected = new Transition(NodaConstants.UnixEpoch, Offset.Zero); Assert.AreEqual(expected, actual); }
public void Next_BeforeFirstYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.Next(Instant.MinValue, Offset.Zero, Offset.Zero); Transition? expected = new Transition(NodaConstants.UnixEpoch, Offset.Zero); Assert.AreEqual(expected, actual); }
public object Clone() { Transition t = new Transition(); t.action = this.action; t.weight = this.weight; t.stateId = this.stateId; return t; }
public void AddingTransitionTwiceThrowsException() { var s = new State(); var t = new Transition(); t.SourceState = s; s.Transitions.Add(t); // Exception: Cannot add duplicate. t was already added before. }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="transitions">The transition instances stored in a contiguous array.</param> /// <param name="count">The number of transitions contained in the set; not all of these transitions are valid.</param> /// <param name="transitionSize">The size of a single transition in bytes.</param> public TransitionEnumerator(Transition* transitions, int count, int transitionSize) : this() { _transitions = (byte*)transitions; _count = count; _transitionSize = transitionSize; _current = -1; }
public void Next_FirstYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, Offset.Zero); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.Next(Instant.UnixEpoch, Offset.Zero, Offset.Zero); Transition? expected = new Transition(new Instant(Instant.UnixEpoch.Ticks + (1 * TicksPerStandardYear)), Offset.Zero, Offset.Zero); Assert.AreEqual(expected, actual); }
public HMM() { State = new State(); Observed = new Observed(); InitialState = new InitialStateProbability(); Transition = new Transition(); Complex = new Complex(); }
public StateID GetOutputState(Transition transition) { if (transitionMap.ContainsKey(transition)) { return transitionMap[transition]; } return StateID.NullStateID; }
protected override void SetUp() { go = new GameObject(); condition = new TestDebugCondition(); condition2 = new TestDebugCondition(); context = go.AddComponent<Context>(); transition = new Transition(target, new Condition[]{ condition, condition2 }); }
public void PreviousOrSame_AfterLastYear() { var januaryFirstMidnight = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight); var recurrence = new ZoneRecurrence("bob", Offset.Zero, januaryFirstMidnight, 1970, 1972); Transition? actual = recurrence.PreviousOrSame(Instant.MaxValue, Offset.Zero, Offset.Zero); Transition? expected = new Transition(Instant.FromUtc(1972, 1, 1, 0, 0), Offset.Zero); Assert.AreEqual(expected, actual); }
void Awake () { slot = NamedBehavior.GetOrCreateComponentByName<State>(gameObject, "slot"); drop = NamedBehavior.GetOrCreateComponentByName<Transition>(gameObject, "deposit"); remove = NamedBehavior.GetOrCreateComponentByName<Transition>(gameObject, "remove"); valid_positions = new Dictionary<GameObject, Vector3>(); score_data = new GameScores.BasketSingleScore(); score_data.id = rx_baskets.Count+1; rx_baskets.Add(this); }
void Start () { character = transform; fieldOfView = Camera.main.fieldOfView; cameraTransform = GetComponentInChildren<Camera>().transform; m_CharacterTargetRot = character.localRotation; m_CameraTargetRot = cameraTransform.localRotation; transition = GameObject.FindObjectOfType<Transition>(); }
/// <summary> /// Determines if this sphere collides with anything during its transition /// </summary> /// <param name="transition">The transition path for this sphere</param> /// <param name="isCreature">Flag indicates if this sphere is a player / monster</param> /// <returns>The collision result for this transition path</returns> public TransitionState IntersectsSphere(Transition transition, bool isCreature) { var globSphere = transition.SpherePath.GlobalSphere[0]; var disp = globSphere.Center - Center; Sphere globSphere_ = null; Vector3 disp_ = Vector3.Zero; if (transition.SpherePath.NumSphere > 1) { globSphere_ = transition.SpherePath.GlobalSphere[1]; disp_ = globSphere_.Center - Center; } var radsum = globSphere.Radius + Radius - PhysicsGlobals.EPSILON; if (transition.SpherePath.ObstructionEthereal || transition.SpherePath.InsertType == InsertType.Placement) { if (disp.LengthSquared() <= radsum * radsum) { return(TransitionState.Collided); } if (transition.SpherePath.NumSphere > 1) { if (CollidesWithSphere(disp_, radsum)) { return(TransitionState.Collided); } } return(TransitionState.OK); } if (transition.SpherePath.StepDown) { if (isCreature) { return(TransitionState.OK); } return(StepSphereDown(transition, globSphere, ref disp, radsum)); } if (transition.SpherePath.CheckWalkable) { if (CollidesWithSphere(disp, radsum)) { return(TransitionState.Collided); } if (transition.SpherePath.NumSphere > 1) { if (CollidesWithSphere(disp_, radsum)) { return(TransitionState.Collided); } } return(TransitionState.OK); } if (!transition.SpherePath.Collide) { if (transition.ObjectInfo.State.HasFlag(ObjectInfoState.Contact) || transition.ObjectInfo.State.HasFlag(ObjectInfoState.OnWalkable)) { if (CollidesWithSphere(disp, radsum)) { return(StepSphereUp(transition, globSphere, disp, radsum)); } if (transition.SpherePath.NumSphere > 1) { if (CollidesWithSphere(disp_, radsum)) { return(SlideSphere(transition, globSphere_, disp_, radsum, 1)); } } return(TransitionState.OK); } else if (transition.ObjectInfo.State.HasFlag(ObjectInfoState.PathClipped)) { if (CollidesWithSphere(disp, radsum)) { return(CollideWithPoint(transition, globSphere, disp, radsum, 0)); } } else { if (CollidesWithSphere(disp, radsum)) { return(LandOnSphere(transition, globSphere, disp, radsum)); } if (transition.SpherePath.NumSphere > 1) { if (CollidesWithSphere(disp_, radsum)) { return(CollideWithPoint(transition, globSphere_, disp_, radsum, 1)); } } } return(TransitionState.OK); } if (!isCreature) { return(TransitionState.OK); } if (!CollidesWithSphere(disp, radsum)) { if (transition.SpherePath.NumSphere > 1) { if (!CollidesWithSphere(disp_, radsum)) { return(TransitionState.OK); } } } // handles movement interpolation var blockOffset = transition.SpherePath.GetCurPosCheckPosBlockOffset(); var movement = transition.SpherePath.GlobalCurrCenter[0].Center - globSphere.Center - blockOffset; radsum += PhysicsGlobals.EPSILON; var lenSq = movement.LengthSquared(); var diff = -Vector3.Dot(movement, disp); if (Math.Abs(lenSq) < PhysicsGlobals.EPSILON) { return(TransitionState.Collided); } var t = Math.Sqrt(diff * diff - (disp.LengthSquared() - radsum * radsum) * lenSq) + diff; // solve for t if (t > 1) { t = diff * 2 - t; } var time = (float)t / lenSq; var timecheck = (1 - time) * transition.SpherePath.WalkInterp; if (timecheck < transition.SpherePath.WalkableAllowance && timecheck < -0.1f) { return(TransitionState.Collided); } movement *= time; disp = (disp + movement) / radsum; if (!transition.SpherePath.IsWalkableAllowable(disp.Z)) { return(TransitionState.OK); } var disp2 = globSphere.Center - disp * globSphere.Radius; var contactPlane = new Plane(disp, -Vector3.Dot(disp, disp2)); transition.CollisionInfo.SetContactPlane(contactPlane, true); transition.CollisionInfo.ContactPlaneCellID = transition.SpherePath.CheckPos.ObjCellID; transition.SpherePath.WalkInterp = timecheck; transition.SpherePath.AddOffsetToCheckPos(movement, globSphere.Radius); return(TransitionState.Adjusted); }
/// <summary> /// This method returns the new state the FSM should be if /// this state receives a transition /// </summary> public FSMStateID GetOutputState(Transition trans) { return(map[trans]); }
/// <summary> /// Attempts to move the sphere down from a collision /// </summary> public TransitionState StepSphereDown(Transition transition, Sphere checkPos, ref Vector3 disp, float radsum) { var path = transition.SpherePath; var collisions = transition.CollisionInfo; if (!CollidesWithSphere(disp, radsum)) { if (path.NumSphere <= 1) { return(TransitionState.OK); } var disp_ = path.GlobalSphere[1].Center - Center; if (!CollidesWithSphere(disp_, radsum)) { return(TransitionState.OK); } } var stepDown = path.StepDownAmt * path.WalkInterp; if (Math.Abs(stepDown) < PhysicsGlobals.EPSILON) { return(TransitionState.Collided); } radsum += PhysicsGlobals.EPSILON; var val = Math.Sqrt(radsum * radsum - (disp.X * disp.X + disp.Y * disp.Y)); var scaledStep = (float)(val - disp.Z) / stepDown; var timecheck = -scaledStep * path.WalkInterp; if (timecheck >= path.WalkInterp || timecheck < -0.1f) { return(TransitionState.Collided); } var interp = stepDown * scaledStep; var invRadSum = 1.0f / radsum; // modifies disp? //var _disp = new Vector3(disp.X, disp.Y, disp.Z + interp) * invRadSum; disp = new Vector3(disp.X, disp.Y, disp.Z + interp) * invRadSum; if (disp.Z <= path.WalkableAllowance) { return(TransitionState.OK); } var scaledDisp = disp * Radius + Center; var restPlane = new Plane(disp, -Vector3.Dot(disp, scaledDisp)); collisions.SetContactPlane(restPlane, true); collisions.ContactPlaneCellID = path.CheckPos.ObjCellID; path.WalkInterp = timecheck; var offset = new Vector3(0, 0, interp); path.AddOffsetToCheckPos(offset, checkPos.Radius); return(TransitionState.Adjusted); }
public bool ContainsKey(string key, Transition origin) { return(GoalVariables.ContainsKey(origin.GetType() + "-" + origin.ParentGoal.name + "-" + key)); }
private void TransitionBetweenStates(NFAState a, NFAState b, int label) { Transition e = new Transition(label, b); a.AddTransition(e); }
public ConfigMount() { InitializeComponent(); var delay = new Transition(new TransitionType_Linear(2000)); var fadeIn = new Transition(new TransitionType_Linear(800)); _ErrorTransition = new[] { delay, fadeIn }; _NoErrorTransition = new Transition(new TransitionType_Linear(10)); LNK_wiki.MouseEnter += (s, e) => FadeLinkTo((LinkLabel)s, Color.CornflowerBlue); LNK_wiki.MouseLeave += (s, e) => FadeLinkTo((LinkLabel)s, Color.WhiteSmoke); SetErrorMessageOpacity(); if (MainV2.comPort.MAV.cs.firmware == Firmwares.ArduPlane) { mavlinkComboBoxTilt.Items.AddRange(Enum.GetNames(typeof(Channelap))); mavlinkComboBoxRoll.Items.AddRange(Enum.GetNames(typeof(Channelap))); mavlinkComboBoxPan.Items.AddRange(Enum.GetNames(typeof(Channelap))); CMB_shuttertype.Items.AddRange(Enum.GetNames(typeof(ChannelCameraShutter))); } else { mavlinkComboBoxTilt.Items.AddRange(Enum.GetNames(typeof(Channelac))); mavlinkComboBoxRoll.Items.AddRange(Enum.GetNames(typeof(Channelac))); mavlinkComboBoxPan.Items.AddRange(Enum.GetNames(typeof(Channelac))); CMB_shuttertype.Items.AddRange(Enum.GetNames(typeof(ChannelCameraShutter))); } string remove = "SERVO"; //cleanup list based on version if (MainV2.comPort.MAV.param.ContainsKey("SERVO1_MIN")) { remove = "RC"; } for (int i = 0; i < mavlinkComboBoxTilt.Items.Count; i++) { var item = mavlinkComboBoxTilt.Items[i] as string; if (item.StartsWith(remove)) { mavlinkComboBoxTilt.Items.Remove(mavlinkComboBoxTilt.Items[i]); i--; continue; } } for (int i = 0; i < mavlinkComboBoxRoll.Items.Count; i++) { var item = mavlinkComboBoxRoll.Items[i] as string; if (item.StartsWith(remove)) { mavlinkComboBoxRoll.Items.Remove(mavlinkComboBoxRoll.Items[i]); i--; continue; } } for (int i = 0; i < mavlinkComboBoxPan.Items.Count; i++) { var item = mavlinkComboBoxPan.Items[i] as string; if (item.StartsWith(remove)) { mavlinkComboBoxPan.Items.Remove(mavlinkComboBoxPan.Items[i]); i--; continue; } } for (int i = 0; i < CMB_shuttertype.Items.Count; i++) { var item = CMB_shuttertype.Items[i] as string; if (item.StartsWith(remove)) { CMB_shuttertype.Items.Remove(CMB_shuttertype.Items[i]); i--; continue; } } CMB_mnt_type.setup(ParameterMetaDataRepository.GetParameterOptionsInt("MNT_TYPE", MainV2.comPort.MAV.cs.firmware.ToString()), "MNT_TYPE", MainV2.comPort.MAV.param); }
private void Start() { transition = GameObject.Find("Transition").GetComponent <Transition>(); }
public override void OnInspectorGUI() { serializedObject.Update(); NGUIEditorTools.SetLabelWidth(100f); UIToggle toggle = target as UIToggle; GUILayout.Space(6f); GUI.changed = false; GUILayout.BeginHorizontal(); SerializedProperty sp = NGUIEditorTools.DrawProperty("Group", serializedObject, "group", GUILayout.Width(120f)); GUILayout.Label(" - zero means 'none'"); GUILayout.EndHorizontal(); EditorGUI.BeginDisabledGroup(sp.intValue == 0); NGUIEditorTools.DrawProperty(" State of 'None'", serializedObject, "optionCanBeNone"); EditorGUI.EndDisabledGroup(); NGUIEditorTools.DrawProperty("Starting State", serializedObject, "startsActive"); NGUIEditorTools.SetLabelWidth(80f); if (NGUIEditorTools.DrawMinimalisticHeader("State Transition")) { NGUIEditorTools.BeginContents(true); SerializedProperty sprite = serializedObject.FindProperty("activeSprite"); SerializedProperty animator = serializedObject.FindProperty("animator"); SerializedProperty animation = serializedObject.FindProperty("activeAnimation"); SerializedProperty tween = serializedObject.FindProperty("tween"); if (sprite.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Sprite", sprite, false); serializedObject.DrawProperty("invertSpriteState"); } else if (animator.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Animator", animator, false); } else if (animation.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Animation", animation, false); } else if (tween.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Tween", tween, false); } else { NGUIEditorTools.DrawProperty("Sprite", serializedObject, "activeSprite"); NGUIEditorTools.DrawProperty("Animator", animator, false); NGUIEditorTools.DrawProperty("Animation", animation, false); NGUIEditorTools.DrawProperty("Tween", tween, false); } if (serializedObject.isEditingMultipleObjects) { NGUIEditorTools.DrawProperty("Instant", serializedObject, "instantTween"); } else { GUI.changed = false; Transition tr = toggle.instantTween ? Transition.Instant : Transition.Smooth; GUILayout.BeginHorizontal(); tr = (Transition)EditorGUILayout.EnumPopup("Transition", tr); NGUIEditorTools.DrawPadding(); GUILayout.EndHorizontal(); if (GUI.changed) { NGUIEditorTools.RegisterUndo("Toggle Change", toggle); toggle.instantTween = (tr == Transition.Instant); NGUITools.SetDirty(toggle); } } NGUIEditorTools.EndContents(); } NGUIEditorTools.DrawEvents("On Value Change", toggle, toggle.onChange); serializedObject.ApplyModifiedProperties(); }
public TestTransition() { ResetForValidation(); _productTransition = new Transition(); }
//ObjectPositioning(type); } } if (target && Vector3.Distance(this.transform.position, target.transform.position) >= breakDistance) { PutDown(); } } } public void PickUp (Rigidbody body) { //check if the object is already selected, remove it from list if (heldObject && _selectable != null) { rm.RemoveFromList(target.gameObject, true, false); rm.selectedObjs.Remove(target.gameObject); } target = body; // Set the target heldObject = target.gameObject; //have the object do the pickup changes! _holdable.DoPickup(); //play sounds for pickup! Toolbox.Instance.SetVolume(audioSource); audioSource.clip = pickupClip; audioSource.Play(); } public void PutDown () { //drop the object _holdable.Drop(); _holdable = null; _selectable = null; _rObject = null; heldObject = null; //remove from the list target = null; //plays sound effect Toolbox.Instance.SetVolume(audioSource); audioSource.clip = dropClip; audioSource.Play(); } private void PrepareForPickup() { if (this.gameObject.layer == 15) { newLayerMask.value = LayerMaskController.Laser; } //layermask value of layer 10 is 1024 else if (this.gameObject.layer == 16) { newLayerMask.value = LayerMaskController.Real; } //layermask value of layer 11 is 2048 Ray r = new Ray(mainCamera.transform.position, mainCamera.transform.forward); RaycastHit hit; if (Physics.Raycast(r, out hit, MaxPickupDistance, newLayerMask.value)) // Otherwise, if target was null, shoot a ray where we are aiming. { Rigidbody body = hit.collider.attachedRigidbody; _rObject = body.GetComponent<ReticleObject>(); _holdable = _rObject as IHoldable; _selectable = _rObject as ISelectable; Transition transition = body.GetComponent<Transition>(); //for picking up actual objects if (_holdable != null && body && ((body.gameObject.layer + 5) == this.gameObject.layer) && !CheckPlayerStance(body.gameObject) && transition && !transition.GetTransitioning()) { PickUp(body); } } } public void KillPickup() { target = null; heldObject = null; _holdable = null; _selectable = null; _rObject = null; } private bool CheckPlayerStance(GameObject obj) {
public void SetVariable(string key, string value, Transition origin) { GoalVariables[origin.GetType() + "-" + origin.ParentGoal.name + "-" + key] = value; }
public void SetTransition(Transition t) { fsm.PerformTransition(t); }
public void Append(BlendShapePreset clipPreset, Transition <float> transition) => Append(BlendShapeKeyCache.Get(clipPreset), transition);
public override void DrawWindow(Node b) { EditorGUILayout.LabelField(""); Node enterNode = BehaviourNodeEditor.settings.currentGraph.GetNodeWithIndex(b.enterNode); if (enterNode == null) { return; } if (enterNode.stateRef.currentState == null) { BehaviourNodeEditor.settings.currentGraph.DeleteNode(b.id); return; } Transition transition = enterNode.stateRef.currentState.GetTransition(b.transRef.transitionId); if (transition == null) { return; } transition.condition = (Condition)EditorGUILayout.ObjectField(transition.condition, typeof(Condition), false); if (transition.condition == null) { EditorGUILayout.LabelField("No Condition!"); b.isAssigned = false; } else { b.isAssigned = true; if (b.isDuplicate) { EditorGUILayout.LabelField("Duplicate Condition"); } else { GUILayout.Label(transition.condition.description); Node targetNode = BehaviourNodeEditor.settings.currentGraph.GetNodeWithIndex(b.targetNode); if (targetNode != null) { if (!targetNode.isDuplicate) { transition.targetState = targetNode.stateRef.currentState; } else { transition.targetState = null; } } else { transition.targetState = null; } } } if (b.transRef.previousCondition != transition.condition) { b.transRef.previousCondition = transition.condition; b.isDuplicate = BehaviourNodeEditor.settings.currentGraph.isTransitionDuplicate(b); if (!b.isDuplicate) { BehaviourNodeEditor.forceSetDirty = true; } } }
public FighterSM() { states = new State[4]; State statePursue = new State(); statePursue.id = StateID.Pursue; statePursue.during = State_Pursue; statePursue.transitions = new Transition[1]; states[0] = statePursue; State stateEvade = new State(); stateEvade.id = StateID.Evade; stateEvade.during = State_Evade; stateEvade.transitions = new Transition[1]; states[1] = stateEvade; State stateReversal = new State(); stateReversal.id = StateID.Reversal; stateReversal.during = State_Reversal; stateReversal.transitions = new Transition[1]; states[2] = stateReversal; State stateAvoidWall = new State(); stateAvoidWall.id = StateID.AvoidWall; stateAvoidWall.during = State_AvoidWall; stateAvoidWall.transitions = new Transition[1]; states[3] = stateAvoidWall; currentState = statePursue; Transition transitionPursueEvade = new Transition(); transitionPursueEvade.from = statePursue; transitionPursueEvade.to = stateEvade; transitionPursueEvade.cond = TransitionCond_Pursue_Evade; statePursue.transitions[0] = transitionPursueEvade; Transition transitionEvadeReversal = new Transition(); transitionEvadeReversal.from = stateEvade; transitionEvadeReversal.to = stateReversal; transitionEvadeReversal.cond = TransitionCond_Evade_Reversal; stateEvade.transitions[0] = transitionEvadeReversal; Transition transitionReversalPursue = new Transition(); transitionReversalPursue.from = stateReversal; transitionReversalPursue.to = statePursue; transitionReversalPursue.cond = TransitionCond_Reversal_Pursue; stateReversal.transitions[0] = transitionReversalPursue; Transition transitionAvoidWallPursue = new Transition(); transitionAvoidWallPursue.from = stateAvoidWall; transitionAvoidWallPursue.to = statePursue; transitionAvoidWallPursue.cond = TransitionCond_AvoidWall_Pursue; stateAvoidWall.transitions[0] = transitionAvoidWallPursue; }
private void CreateStateMachine() { // Let's create a state machine that manages all states and transitions. _stateMachine = new StateMachine(); // ----- First we need to define all possible states of the game component: // The initial state is the "Loading" state. In this state a "Loading..." // text is rendered and all required assets are loaded in the background. var loadingState = new State { Name = "Loading" }; loadingState.Enter += OnEnterLoadingScreen; loadingState.Exit += OnExitLoadingScreen; // The second state is the "Start" state. Once loading is finished the text // "Press Start button" is shown until the users presses the Start button // on the gamepad. var startState = new State { Name = "Start" }; startState.Enter += OnEnterStartScreen; startState.Update += OnUpdateStartScreen; startState.Exit += OnExitStartScreen; // The "Menu" state represents the main menu. It provides buttons to start // the game, show sub menus, and exit the game. var menuState = new State { Name = "Menu" }; menuState.Enter += OnEnterMenuScreen; menuState.Exit += OnExitMenuScreen; // The "SubMenu" is just a dummy menu containing a few buttons. It is shown // whenever a sub menu is selected in the main menu. var subMenuState = new State { Name = "SubMenu" }; subMenuState.Enter += OnEnterSubMenuScreen; subMenuState.Update += OnUpdateSubMenuScreen; subMenuState.Exit += OnExitSubMenuScreen; // The "Game" state is a placeholder for the actual game content. var gameState = new State { Name = "Game" }; gameState.Enter += OnEnterGameScreen; gameState.Update += OnUpdateGameScreen; gameState.Exit += OnExitGameScreen; // Register the states in the state machine. _stateMachine.States.Add(loadingState); _stateMachine.States.Add(startState); _stateMachine.States.Add(menuState); _stateMachine.States.Add(subMenuState); _stateMachine.States.Add(gameState); // Optional: Define the initially selected state. // (If not set explicitly then the first state in the list is used as the // initial state.) _stateMachine.States.InitialState = loadingState; // ----- Next we can define the allowed transitions between states. // The "Loading" screen will transition to the "Start" screen once all assets // are loaded. The assets are loaded in the background. The background worker // sets the flag _allAssetsLoaded when it has finished. // The transition should fire automatically. To achieve this we can set FireAlways // to true and define a Guard. A Guard is a condition that needs to be fulfilled // to enable the transition. This way the game component automatically switches // from the "Loading" state to the "Start" state once the loading is complete. var loadToStartTransition = new Transition { Name = "LoadingToStart", TargetState = startState, FireAlways = true, // Always trigger the transition, if the guard allows it. Guard = () => _allAssetsLoaded, // Enable the transition when _allAssetsLoaded is true. }; loadingState.Transitions.Add(loadToStartTransition); // The remaining transition need to be triggered manually. // The "Start" screen will transition to the "Menu" screen. var startToMenuTransition = new Transition { Name = "StartToMenu", TargetState = menuState, }; startState.Transitions.Add(startToMenuTransition); // The "Menu" screen can transition to the "Game" screen or to the "SubMenu". var menuToGameTransition = new Transition { Name = "MenuToGame", TargetState = gameState, }; var menuToSubMenuTransition = new Transition { Name = "MenuToSubMenu", TargetState = subMenuState, }; menuState.Transitions.Add(menuToGameTransition); menuState.Transitions.Add(menuToSubMenuTransition); // The "Game" screen will transition back to the "Menu" screen. var gameToMenuTransition = new Transition { Name = "GameToMenu", TargetState = menuState, }; gameState.Transitions.Add(gameToMenuTransition); // The "SubMenu" can transition to back to the "Menu" screen. var subMenuToMenuTransition = new Transition { Name = "SubMenuToMenu", TargetState = menuState, }; subMenuState.Transitions.Add(subMenuToMenuTransition); }
private bool Equals(Transition <TS> other) { return(Equals(FsmRef, other.FsmRef) && EqualityComparer <TS> .Default.Equals(From, other.From) && EqualityComparer <TS> .Default.Equals(To, other.To)); }
void Start() { //INICIALIZAMOS LA DATA DEL EXTERIOR kinPidgeotto = pidgeotto.kineticsAgent; steeringPidgeotto = pidgeotto.steeringAgent; graph = graphComponent.graph; aStar = new PathFindAStar(graph, null, null, null, walkable); seek = new Seek(kinPidgeotto, kinPidgeotto, pidgeotto.maxspeed); //obstaculos GameObject[] obstacles = GameObject.FindGameObjectsWithTag("Obstacle"); obstacle_data[] obstaclesData = new obstacle_data[obstacles.Length]; for (int k = 0; k < obstacles.Length; k++) { obstaclesData[k] = obstacles[k].GetComponent <obstacle_data>(); } //COMENZAMOS A CONSTRUIR LA MAQUINA DE ESTADOS //1. ACCIONES: UpdateAStarRandom updateAStar = new UpdateAStarRandom(aStar, graph, kinPidgeotto, null, walkable); FollowPathOfPoints followPath = new FollowPathOfPoints(steeringPidgeotto, seek, null, false); UpdateFollowPathWithAstar updateFollow = new UpdateFollowPathWithAstar(followPath, aStar, obstaclesData); //2. ESTADOS: List <Action> entryActions; //aqui iremos guardanndo todas las acciondes de entrada List <Action> exitActions; //aqui iremos guardanndo todas las acciones de salida List <Action> actions; //aqui guardaremos todas las acciones intermedias //2.a estado para seguir camino entryActions = new List <Action>() { }; //al entrar al estado ponemos un corazon actions = new List <Action>() { followPath }; //durante el estado perseguimos al enamorado exitActions = new List <Action>() { }; //al salir quitamos el corazon State followPathState = new State(actions, entryActions, exitActions); //3. CONDICIONES: ArrivedToPosition arrived = new ArrivedToPosition(new Vector3(), transform, 10f); updateAStar.arrived = arrived; //4. TRANSICIONES: List <Action> noActions = new List <Action>(); List <Action> transitionActions; transitionActions = new List <Action>() { updateAStar, updateFollow }; Transition pathEnd = new Transition(arrived, transitionActions, followPathState); //4.1 AGREGAMOS TRANSICIONES A ESTADOS List <Transition> transitions = new List <Transition>() { pathEnd }; followPathState.transitions = transitions; //5 MAQUINA DE ESTADOS State[] states = new State[] { followPathState }; pidgeottoMachine = new StateMachine(states, followPathState); updateAStar.DoAction();//esto es para inicializar el primer camino updateFollow.DoAction(); }
/// <summary> /// Determines if this sphere collides with any other spheres during its transitions /// </summary> public TransitionState IntersectsSphere(Position position, float scale, Transition transition, bool isCreature) { var globPos = transition.SpherePath.CheckPos.LocalToGlobal(position, Center * scale); return(new Sphere(globPos, Radius * scale).IntersectsSphere(transition, isCreature)); }
public float teamDistanceToTarget = 100.0f; //Tracks the distance from the teamCenterPoint to the teamTarget //======================================================================================================================================= /// <summary> /// Initializes a Commander_FSM object. /// </summary> /// <returns></returns> public void Start() { Team teamRED = GameManager.instance.teams[0]; // The team will be triggered to use orders based on the current strategic state SetTeamUseOrders(false); teamCount = teamRED.members.Count; teamTarget = GameManager.instance.teams[1].members[0]; //Define Strategic Transitions var teammateDeath = new Transition(State.Strategic_Regroup, (manager) => { return(teamCountDelta > 0); }); var targetEliminated = new Transition(State.Strategic_FocusFire, (manager) => { return(teamTarget.getHealth() <= 0.0f); }); var teamFannedOut = new Transition(State.Strategic_FocusFire, (manager) => { return(GetTeamAvgDistanceFromTeamCenter() > 6.0f); }); var teamGrouped = new Transition(State.Strategic_HoldPosition, (manager) => { return(GetTeamAvgDistanceFromTeamCenter() < 5.0f); }); var teamLocationReached = new Transition(State.Strategic_FocusFire, (manager) => { var TeamRED = GameManager.instance.teams[0].members; bool inPosition = false; int numberOfTeamInPosition = 0; foreach (var teammate in TeamRED) { if (Mathf.Abs(Vector3.Distance(teammate.transform.position, teammate.destination)) < 3.0f) { numberOfTeamInPosition += 1; } } if (numberOfTeamInPosition == TeamRED.Count - 1) { inPosition = true; } return(inPosition); }); var teamAmbush = new Transition(State.Strategic_MoveToFiringPosition, (manager) => { return(teamDistanceToTarget < 12.0f); }); var targetHidden = new Transition(State.Strategic_MoveToFiringPosition, (manager) => { var TeamRED = GameManager.instance.teams[0].members; int numberOfVisible = 0; foreach (var teammate in TeamRED) { if (manager.tileManager.PositionCanSeePosition(teammate.transform.position, teamTarget.transform.position)) { numberOfVisible += 1; } } return(numberOfVisible > (TeamRED.Count / 2)); }); // Focus fire on an enemy when it becomes weak var enemyWeak = new Transition(State.Strategic_MoveToFiringPosition, (manager) => { var teamBlue = manager.teams[1]; foreach (var enemy in teamBlue.members) { if (enemy.HasLowHealth()) { return(true); } } return(false); }); // Define null strategy transitions var nullTransitions = new List <Transition>(); nullTransitions.Add(enemyWeak); //Define Regroup Transitions var regroupTransitions = new List <Transition>(); regroupTransitions.Add(teamGrouped); //Define FanOut Transitions var fanOutTransitions = new List <Transition>(); fanOutTransitions.Add(teamFannedOut); //Define FocusFire Transitions var focusFireTransitions = new List <Transition>(); focusFireTransitions.Add(targetEliminated); focusFireTransitions.Add(targetHidden); focusFireTransitions.Add(teammateDeath); //Define MoveToFiringPosition Transitions var moveToFiringPositionTransitions = new List <Transition>(); moveToFiringPositionTransitions.Add(teamLocationReached); //Define HoldPosition Transitions var holdPositionTransitions = new List <Transition>(); holdPositionTransitions.Add(teamAmbush); holdPositionTransitions.Add(teammateDeath); //Define Dictionary of State/Transition Pairs - to be used by the Strategic State Machine var transitions = new Dictionary <State, IEnumerable <Transition> >(); transitions.Add(State.Strategic_FanOut, fanOutTransitions); transitions.Add(State.Strategic_FocusFire, focusFireTransitions); transitions.Add(State.Strategic_Regroup, regroupTransitions); transitions.Add(State.Strategic_HoldPosition, holdPositionTransitions); transitions.Add(State.Strategic_MoveToFiringPosition, moveToFiringPositionTransitions); transitions.Add(State.Strategic_Null, nullTransitions); //Define and Create the Strategic State Machine strategyFSM = new StrategicStateMachine(State.Strategic_HoldPosition, transitions); strategyFSM.AddStateBehavior(State.Strategic_FanOut, new FanOutState()); strategyFSM.AddStateBehavior(State.Strategic_FocusFire, new FocusFireState()); strategyFSM.AddStateBehavior(State.Strategic_Regroup, new RegroupState()); strategyFSM.AddStateBehavior(State.Strategic_MoveToFiringPosition, new MoveToFiringPosition()); strategyFSM.AddStateBehavior(State.Strategic_HoldPosition, new HoldPositionState()); }//END: Start() Function
protected internal virtual void VisitState(ATNState p) { int edge; if (p.NumberOfTransitions > 1) { ErrorHandler.Sync(this); edge = Interpreter.AdaptivePredict(TokenStream, ((DecisionState)p).decision, RuleContext); } else { edge = 1; } Transition transition = p.Transition(edge - 1); switch (transition.TransitionType) { case TransitionType.EPSILON: { if (pushRecursionContextStates.Get(p.stateNumber) && !(transition.target is LoopEndState)) { InterpreterRuleContext ctx = new InterpreterRuleContext(_parentContextStack.Peek().Item1, _parentContextStack.Peek().Item2, RuleContext.RuleIndex); PushNewRecursionContext(ctx, _atn.ruleToStartState[p.ruleIndex].stateNumber, RuleContext.RuleIndex); } break; } case TransitionType.ATOM: { Match(((AtomTransition)transition).token); break; } case TransitionType.RANGE: case TransitionType.SET: case TransitionType.NOT_SET: { if (!transition.Matches(TokenStream.LA(1), TokenConstants.MinUserTokenType, 65535)) { ErrorHandler.RecoverInline(this); } MatchWildcard(); break; } case TransitionType.WILDCARD: { MatchWildcard(); break; } case TransitionType.RULE: { RuleStartState ruleStartState = (RuleStartState)transition.target; int ruleIndex = ruleStartState.ruleIndex; InterpreterRuleContext ctx_1 = new InterpreterRuleContext(RuleContext, p.stateNumber, ruleIndex); if (ruleStartState.isPrecedenceRule) { EnterRecursionRule(ctx_1, ruleStartState.stateNumber, ruleIndex, ((RuleTransition)transition).precedence); } else { EnterRule(ctx_1, transition.target.stateNumber, ruleIndex); } break; } case TransitionType.PREDICATE: { PredicateTransition predicateTransition = (PredicateTransition)transition; if (!Sempred(RuleContext, predicateTransition.ruleIndex, predicateTransition.predIndex)) { throw new FailedPredicateException(this); } break; } case TransitionType.ACTION: { ActionTransition actionTransition = (ActionTransition)transition; Action(RuleContext, actionTransition.ruleIndex, actionTransition.actionIndex); break; } case TransitionType.PRECEDENCE: { if (!Precpred(RuleContext, ((PrecedencePredicateTransition)transition).precedence)) { throw new FailedPredicateException(this, string.Format("precpred(_ctx, {0})", ((PrecedencePredicateTransition)transition).precedence)); } break; } default: { throw new NotSupportedException("Unrecognized ATN transition type."); } } State = transition.target.stateNumber; }
public void Append(BlendShapeKey clipKey, Transition <float> transition) { transitions.Remove(clipKey); transitions.Add(clipKey, new TransitionPlayer <float>(transition, VRM.GetValue(clipKey))); }
/************************************************************************************************************************/ public void DoGUI() { GUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.LabelField("Preview Details", "(Not Serialized)"); DoModelGUI(); DoAnimatorSelectorGUI(); using (ObjectPool.Disposable.AcquireContent(out var label, "Previous Animation", "The animation for the preview to play before the target transition")) { DoAnimationFieldGUI(label, ref _PreviousAnimation, (clip) => _PreviousAnimation = clip); } var animancer = _Instance._Scene.Animancer; DoCurrentAnimationGUI(animancer); using (ObjectPool.Disposable.AcquireContent(out var label, "Next Animation", "The animation for the preview to play after the target transition")) { DoAnimationFieldGUI(label, ref _NextAnimation, (clip) => _NextAnimation = clip); } if (animancer != null) { if (animancer.IsGraphPlaying) { if (GUILayout.Button("Pause", EditorStyles.miniButton)) { animancer.PauseGraph(); } } else { using (new EditorGUI.DisabledScope(!Transition.IsValid())) { if (GUILayout.Button("Play Transition", EditorStyles.miniButton)) { if (_PreviousAnimation != null && _PreviousAnimation.length > 0) { _Instance._Scene.Animancer.Stop(); var fromState = animancer.States.GetOrCreate(PreviousAnimationKey, _PreviousAnimation, true); animancer.Play(fromState); OnPlayAnimation(); fromState.Time = 0; var warnings = OptionalWarning.UnsupportedEvents.DisableTemporarily(); fromState.Events.endEvent = new AnimancerEvent(1 / fromState.Length, PlayTransition); warnings.Enable(); } else { PlayTransition(); } _Instance._Scene.Animancer.UnpauseGraph(); } } } } GUILayout.EndVertical(); }
/// <summary> /// Returns the next string in lexicographic order that will not put /// the machine into a reject state. /// <para/> /// This method traverses the DFA from the given position in the string, /// starting at the given state. /// <para/> /// If this cannot satisfy the machine, returns <c>false</c>. This method will /// walk the minimal path, in lexicographic order, as long as possible. /// <para/> /// If this method returns <c>false</c>, then there might still be more solutions, /// it is necessary to backtrack to find out. /// </summary> /// <param name="state"> current non-reject state </param> /// <param name="position"> useful portion of the string </param> /// <returns> <c>true</c> if more possible solutions exist for the DFA from this /// position </returns> private bool NextString(int state, int position) { /* * the next lexicographic character must be greater than the existing * character, if it exists. */ int c = 0; if (position < seekBytesRef.Length) { c = seekBytesRef.Bytes[position] & 0xff; // if the next byte is 0xff and is not part of the useful portion, // then by definition it puts us in a reject state, and therefore this // path is dead. there cannot be any higher transitions. backtrack. if (c++ == 0xff) { return(false); } } seekBytesRef.Length = position; visited[state] = curGen; Transition[] transitions = allTransitions[state]; // find the minimal path (lexicographic order) that is >= c for (int i = 0; i < transitions.Length; i++) { Transition transition = transitions[i]; if (transition.Max >= c) { int nextChar = Math.Max(c, transition.Min); // append either the next sequential char, or the minimum transition seekBytesRef.Grow(seekBytesRef.Length + 1); seekBytesRef.Length++; seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)nextChar; state = transition.Dest.Number; /* * as long as is possible, continue down the minimal path in * lexicographic order. if a loop or accept state is encountered, stop. */ while (visited[state] != curGen && !runAutomaton.IsAccept(state)) { visited[state] = curGen; /* * Note: we work with a DFA with no transitions to dead states. * so the below is ok, if it is not an accept state, * then there MUST be at least one transition. */ transition = allTransitions[state][0]; state = transition.Dest.Number; // append the minimum transition seekBytesRef.Grow(seekBytesRef.Length + 1); seekBytesRef.Length++; seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)transition.Min; // we found a loop, record it for faster enumeration if ((finite == false) && !linear && visited[state] == curGen) { SetLinear(seekBytesRef.Length - 1); } } return(true); } } return(false); }
public override void Dispose() { if (IsDisposed) { return; } base.Dispose(); self.Remove(); self = null; SkillAndStateBackGround = null; RedProBar = null; RedText = null; BlueProBar = null; BlueText = null; SkillQ_Loader = null; SkillQ_Bar = null; SkillQ_CDInfo = null; SkillQ_Text = null; SkillQ = null; SkillE_Loader = null; SkillE_Bar = null; SkillE_Text = null; SkillE_CDInfo = null; SkillE = null; SkillW_Loader = null; SkillW_Bar = null; SkillW_Text = null; SkillW_CDInfo = null; SkillW = null; SkillR_Loader = null; SkillR_Bar = null; SkillR_Text = null; SkillR_CDInfo = null; SkillR = null; SkillTalent_Loader = null; SkillTalent_Bar = null; SkillTalent_CDInfo = null; SkillTalent = null; SkillD_Loader = null; SkillD_Bar = null; SkillD_CDInfo = null; SkillD_Text = null; SkillD = null; SkillF_Loader = null; SkillF_Bar = null; SkillF_CDInfo = null; SkillF_Text = null; SkillF = null; SkillAndState = null; n96 = null; Attack = null; Magic = null; Armorpenetration = null; Magicpenetration = null; Armor = null; SpellResistance = null; AttackSpeed = null; ExtraMagic = null; ExtraAttack = null; SkillCD = null; Criticalstrike = null; AttackInfo = null; MoveSpeed = null; SkillCDInfo = null; MagicpenetrationInfo = null; ArmorpenetrationInfo = null; ExtraMagicInfo = null; ExtraAttackInfo = null; CriticalstrikeInfo = null; AttackSpeedInfo = null; SpellResistanceInfo = null; ArmorInfo = null; MagicInfo = null; MoveSpeedInfo = null; DetailData = null; HeroAvatarLoader = null; AvatarBack = null; HeroLevel = null; ExpBar = null; Avatar = null; UIBack = null; t1 = null; t6 = null; t5 = null; t3 = null; t2 = null; t7 = null; Zhuangbei = null; t4 = null; tB = null; BasicSkills = null; n58 = null; GoldenCount = null; Golden = null; ShopAndBack = null; Bottom = null; BuffList = null; DeBuffList = null; SmallMapSprite = null; SmallMapFrame = null; SmallMap = null; GM_BackGround = null; Btn_NoMPCost = null; n198 = null; Btn_NoHPCost = null; n200 = null; Btn_NoCDCost = null; n201 = null; Btn_CreateSpiling = null; n202 = null; Btn_GMController_Enable = null; Btn_GMController_Disable = null; GM = null; Par_GMControllerDis = null; Part_GMControllerEnable = null; }
void Awake() { transition = GameObject.FindWithTag("MainCamera").GetComponent <Transition>(); }
public PetriNet Compile(PetriNet phylum) { String prefix = phylum.ActivityCount + ".internal."; Place p1 = phylum.NewPlace(prefix + "initialized"); Place p2 = phylum.NewPlace(prefix + "closed"); if (startNode == null) { // New Activity phylum.ActivityCount += 1; int currentID = phylum.ActivityCount; // Compile new Empty().Compile(phylum); // Merge phylum.Merge(p1, currentID + ".internal.initialized"); phylum.Merge(p2, currentID + ".internal.closed"); return(phylum); } // Create Steps foreach (FlowNode node in steps) { if (node is FlowStep) { FlowStep step = (FlowStep)node; String prefixStep = prefix + step.Id + "."; Place stp1 = phylum.NewPlace(prefixStep + "start"); Place stp2 = phylum.NewPlace(prefixStep + "next"); phylum.ActivityCount += 1; int currentID = phylum.ActivityCount; // Action Activity step.Action.Compile(phylum); // Connect phylum.Merge(stp1, currentID + ".internal.initialized"); phylum.Merge(stp2, currentID + ".internal.closed"); } else if (node is FlowDecision) { FlowDecision dec = (FlowDecision)node; String prefixStep = prefix + dec.Id + "."; Place dp1 = phylum.NewPlace(prefixStep + "start"); Place condition = phylum.NewPlace(prefixStep + "condition"); Place right = phylum.NewPlace(prefixStep + "true"); Place wrong = phylum.NewPlace(prefixStep + "false"); Transition evalCondition = phylum.NewTransition(prefixStep + "evalcondition"); Transition startTrue = phylum.NewTransition(prefixStep + "starttrue"); Transition startFalse = phylum.NewTransition(prefixStep + "startfalse"); // Connect phylum.NewArc(dp1, evalCondition); phylum.NewArc(evalCondition, condition); phylum.NewArc(condition, startTrue); phylum.NewArc(condition, startFalse); phylum.NewArc(startTrue, right); phylum.NewArc(startFalse, wrong); } else if (node is FlowSwitch) { FlowSwitch swtch = (FlowSwitch)node; String prefixStep = prefix + swtch.Id + "."; Place sp1 = phylum.NewPlace(prefixStep + "start"); Place sdefault = phylum.NewPlace(prefixStep + "default"); // Inner Petri Net Place lastState = sp1; for (int i = 1; i <= swtch.Branches.Count + 1; i++) { if (i <= swtch.Branches.Count) { Place cond = phylum.NewPlace(prefixStep + "condition" + i); Place state = phylum.NewPlace(prefixStep + "case" + i); Transition evalCase = phylum.NewTransition(prefixStep + "evalcase" + i); Transition initCase = phylum.NewTransition(prefixStep + "initcase" + i); phylum.NewArc(lastState, evalCase); phylum.NewArc(evalCase, cond); phylum.NewArc(cond, initCase); phylum.NewArc(initCase, state); // LastState lastState = cond; } else { Transition initDefault = phylum.NewTransition(prefixStep + "initdefault"); phylum.NewArc(lastState, initDefault); phylum.NewArc(initDefault, sdefault); } } } } // Merge // StartNode phylum.Merge(p1, prefix + steps.First(e => e.Id.Equals(startNode)).Id + ".start"); foreach (FlowNode node in steps) { if (node is FlowStep) { FlowStep step = (FlowStep)node; String prefixStep = prefix + step.Id + "."; if (step.Next != null) { phylum.Merge(prefixStep + "next", prefix + step.Next + ".start"); } else { phylum.Merge(p2, prefixStep + "next"); } } else if (node is FlowDecision) { FlowDecision dec = (FlowDecision)node; String prefixDecision = prefix + dec.Id + "."; if (dec.Right != null) { phylum.Merge(prefixDecision + "true", prefix + dec.Right + ".start"); } else { phylum.Merge(p2, prefixDecision + "true"); } if (dec.Wrong != null) { phylum.Merge(prefixDecision + "false", prefix + dec.Wrong + ".start"); } else { phylum.Merge(p2, prefixDecision + "false"); } } else if (node is FlowSwitch) { FlowSwitch swtch = (FlowSwitch)node; String prefixSwitch = prefix + swtch.Id + "."; //Default if (swtch.Default != null) { phylum.Merge(prefixSwitch + "default", prefix + swtch.Default + ".start"); } else { phylum.Merge(p2, prefixSwitch + "default"); } // Branches for (int i = 1; i <= swtch.Branches.Count; i++) { phylum.Merge(prefixSwitch + "case" + i, prefix + swtch.Branches[i - 1] + ".start"); } } } return(phylum); }
/// <summary> /// 初始化状态机 /// </summary> private void InitFSM() { changeIntensity = new State("ChangeIntensity"); changeIntensity.OnEnter += (IState state) => { isReset = true; isAnimation = true; }; changeIntensity.OnUpdate += (float f) => { if (isAnimation) { if (isReset) { if (FadeTo(MaxIntensity)) { isReset = false; isAnimation = false; } } else { if (FadeTo(target)) { isReset = true; } } } else { target = Random.Range(0.3f, 0.7f); isAnimation = true; } }; changeColor = new State("ChangeColor"); changeColor.OnEnter += (IState state) => { isAnimation = false; }; changeColor.OnUpdate += (float f) => { if (isAnimation) { if (colorTimer >= 1f) { isAnimation = false; } else { colorTimer += Time.deltaTime * 1f; myLight.color = Color.Lerp(startColor, targetColor, colorTimer); } } else { float r = Random.Range(0f, 1f); float g = Random.Range(0f, 1f); float b = Random.Range(0f, 1f); targetColor = new Color(r, g, b); startColor = myLight.color; colorTimer = 0f; isAnimation = true; } }; color2Intensity = new Transition(changeColor, changeIntensity); color2Intensity.OnCheck += () => { return(!isChangeColor); }; changeColor.AddTransition(color2Intensity); intensity2color = new Transition(changeIntensity, changeColor); intensity2color.OnCheck += () => { return(isChangeColor); }; changeIntensity.AddTransition(intensity2color); open = new FSMMachine("Open", changeIntensity); open.AddState(changeColor); open.OnEnter += (IState state) => { myLight.intensity = MaxIntensity; }; close = new State("Close"); close.OnEnter += (IState state) => { myLight.intensity = 0f; }; open2Close = new Transition(open, close); open2Close.OnCheck += () => { return(!isOpen); }; open2Close.OnTransition += () => { return(FadeTo(0f)); }; open.AddTransition(open2Close); close2Open = new Transition(close, open); close2Open.OnCheck += () => { return(isOpen); }; close2Open.OnTransition += () => { return(FadeTo(MaxIntensity)); }; close.AddTransition(close2Open); lightFSM = new FSMMachine("LightFSM", open); lightFSM.AddState(close); }
public void Append(string clipName, Transition <float> transition) => Append(BlendShapeKeyCache.Get(clipName), transition);
public override StateGraph CreateGraph() { StateGraph stateGraph = new StateGraph(); LordToil lordToil = stateGraph.StartingToil = stateGraph.AttachSubgraph(new LordJob_Travel(this.chillSpot).CreateGraph()).StartingToil; LordToil_DefendPoint lordToil_DefendPoint = new LordToil_DefendPoint(this.chillSpot, 28f); stateGraph.AddToil(lordToil_DefendPoint); LordToil_TakeWoundedGuest lordToil_TakeWoundedGuest = new LordToil_TakeWoundedGuest(); stateGraph.AddToil(lordToil_TakeWoundedGuest); StateGraph stateGraph2 = new LordJob_TravelAndExit(IntVec3.Invalid).CreateGraph(); LordToil startingToil2 = stateGraph.AttachSubgraph(stateGraph2).StartingToil; LordToil target = stateGraph2.lordToils[1]; LordToil_ExitMap lordToil_ExitMap = new LordToil_ExitMap(LocomotionUrgency.Walk, true); stateGraph.AddToil(lordToil_ExitMap); Transition transition = new Transition(lordToil, startingToil2); transition.AddSources(lordToil_DefendPoint); transition.AddTrigger(new Trigger_PawnExperiencingDangerousTemperatures()); transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition.AddPreAction(new TransitionAction_EnsureHaveExitDestination()); transition.AddPostAction(new TransitionAction_WakeAll()); stateGraph.AddTransition(transition); Transition transition2 = new Transition(lordToil, lordToil_ExitMap); transition2.AddSources(lordToil_DefendPoint, lordToil_TakeWoundedGuest); transition2.AddSources(stateGraph2.lordToils); transition2.AddTrigger(new Trigger_PawnCannotReachMapEdge()); transition2.AddPreAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); stateGraph.AddTransition(transition2); Transition transition3 = new Transition(lordToil_ExitMap, startingToil2); transition3.AddTrigger(new Trigger_PawnCanReachMapEdge()); transition3.AddPreAction(new TransitionAction_EnsureHaveExitDestination()); transition3.AddPostAction(new TransitionAction_EndAllJobs()); stateGraph.AddTransition(transition3); Transition transition4 = new Transition(lordToil, lordToil_DefendPoint); transition4.AddTrigger(new Trigger_Memo("TravelArrived")); stateGraph.AddTransition(transition4); Transition transition5 = new Transition(lordToil_DefendPoint, lordToil_TakeWoundedGuest); transition5.AddTrigger(new Trigger_WoundedGuestPresent()); transition5.AddPreAction(new TransitionAction_Message("MessageVisitorsTakingWounded".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); stateGraph.AddTransition(transition5); Transition transition6 = new Transition(lordToil_DefendPoint, target); transition6.AddSources(lordToil_TakeWoundedGuest, lordToil); transition6.AddTrigger(new Trigger_BecameColonyEnemy()); transition6.AddPreAction(new TransitionAction_SetDefendLocalGroup()); transition6.AddPostAction(new TransitionAction_WakeAll()); transition6.AddPostAction(new TransitionAction_EndAllJobs()); stateGraph.AddTransition(transition6); Transition transition7 = new Transition(lordToil_DefendPoint, startingToil2); transition7.AddTrigger(new Trigger_TicksPassed(Rand.Range(8000, 22000))); transition7.AddPreAction(new TransitionAction_Message("VisitorsLeaving".Translate(this.faction.Name))); transition7.AddPostAction(new TransitionAction_WakeAll()); transition7.AddPreAction(new TransitionAction_EnsureHaveExitDestination()); stateGraph.AddTransition(transition7); return(stateGraph); }