protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { // Check to see whether the Motion API is supported on the device. if (!Motion.IsSupported) { MessageBox.Show("the Motion API is not supported on this device."); return; } // If the Motion object is null, initialize it and add a CurrentValueChanged // event handler. if (motion == null) { motion = new Motion(); motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20); motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged); } // Try to start the Motion API. try { motion.Start(); } catch (Exception ex) { MessageBox.Show("unable to start the Motion API."); } }
BvhWriter(string filename, Motion motion) { this.filename = filename; this.motion = motion; writer = new StreamWriter(filename, false, Encoding.ASCII); }
public static Motion GetMotion(int id) { var result = new Motion(); using (var db = CreateConnection()) using (var sql = db.CreateCommand()) { db.Open(); sql.CommandText = @"SELECT id,moderatorId,text,status,redditLink,isInOrder,createDt FROM motion WHERE id = @id LIMIT 1;"; var pId = sql.CreateParameter(); pId.ParameterName = "@id"; pId.Value = id; sql.Parameters.Add(pId); var rs = sql.ExecuteReader(); if (rs.Read()) { result.Id = rs.GetInt32(0); result.Sponsor = GetModerator(rs.GetInt32(1)); result.Text = rs.GetString(2); result.Status = (MotionStatus)rs.GetInt32(3); result.PostUrl = (string)rs.GetValue(4); result.Created = DateTime.Parse(rs.GetString(6)); } rs.Close(); db.Close(); } return result; }
public static BallotCollection GetBallots(Motion motion) { var result = new BallotCollection(); var sql = CreateCommand(); sql.CommandText = @"SELECT id,motionId,moderatorId,choice FROM ballots WHERE motionId = ?motionId"; var pId = sql.CreateParameter(); pId.ParameterName = "?motionId"; pId.Value = motion.Id; sql.Parameters.Add(pId); using (var db = CreateConnection()) { db.Open(); sql.Connection = db; sql.Prepare(); var rs = sql.ExecuteReader(); while (rs.Read()) { result.Add(new Ballot { Id = rs.GetInt32(0), Motion = GetMotion(rs.GetInt32(1)), Moderator = GetModerator(rs.GetInt32(2)), Choice = (Choice)rs.GetInt32(3) }); } db.Close(); } return result; }
private void setupSensors() { // Initialize the combined orientation sensor try { motion = new Motion(); motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(100); motion.CurrentValueChanged += motion_CurrentValueChanged; motion.Start(); } catch { // Print out an error MessageBox.Show("Could not initialize Motion API. This phone does not have the necessary sensors to run this code properly!"); // The kill the current application Application.Current.Terminate(); } // Setup sound output sio = new SoundIO(); sio.audioOutEvent += sio_audioOutEvent; sio.start(); at = new AudioTool(sio.getOutputNumChannels(), sio.getOutputSampleRate()); }
void OnGUI() { GUI.Label(new Rect(5, 4, 80, 18), "Enter a name:"); // Assign name from text field name = EditorGUI.TextField(new Rect(85, 4, 125, 15), name); if (!recording) { // Begin Recording if (GUI.Button(new Rect(5, 28, 50, 18), "Record")) { motion = new Motion(); recording = true; } // Allow Submission of a Recording if (motion.steps.Count > 0) { if (GUI.Button(new Rect(60, 28, 50, 18), "Submit")) { editor.motions.Add(name, motion); editor.motionControl.animation = null; this.Close(); } } } else { // End Recording if (GUI.Button(new Rect(5, 28, 50, 18), "Stop")) { recording = false; editor.motionControl.animation = motion; } } // Cancel Motion Creation if (GUI.Button(new Rect(170, 28, 50, 18), "Cancel")) { editor.motionControl.animation = null; this.Close(); } }
public static Action<TextEditorData> GetEditObjectCharAction (char c, Motion motion) { if (motion == Motion.None) return GetEditObjectCharAction(c); switch (c) { case 'w': return ViActions.InnerWord; case ')': case '}': case ']': case '>': if (motion == Motion.Inner) return ViActions.InnerSymbol (c); else if (motion == Motion.Outer) return ViActions.OuterSymbol (c); else return null; case '"': case '\'': case '`': if (motion == Motion.Inner) return ViActions.InnerQuote (c); else if (motion == Motion.Outer) return ViActions.OuterQuote (c); else return null; default: return null; } }
protected override Motion GetSelectionMotion(int index) { Motion m = new Motion(); m.Axis = new Vector3D(0, 1, 0); m.Z = Owner.PopoutDistance + Owner.ZOffset; m.Y = Owner.YOffset; m.X = Owner.XOffset; ChangeStateForElement(index, Visibility.Visible); Viewport2DVisual3D model = (Viewport2DVisual3D)Owner._modelContainer.Children[index]; LoginGrid loginGrid = (LoginGrid)model.Visual; if (Owner._modelContainer.Children.Count <= 1) { loginGrid.imgMoveToRight.Visibility = Visibility.Collapsed; loginGrid.imgMoveToLeft.Visibility = Visibility.Collapsed; } else { loginGrid.imgMoveToLeft.Visibility = Owner.SelectedIndex < Owner._modelContainer.Children.Count - 1 ? Visibility.Visible : Visibility.Collapsed; loginGrid.imgMoveToRight.Visibility = Owner.SelectedIndex > 0 ? Visibility.Visible : Visibility.Collapsed; } return m; }
public static void Write(string filename, Motion motion) { using (var writer = new BvhWriter(filename, motion)) { writer.Write(); } }
public void Zoom(float scale, float duration) { if (_currentMotion != null) { _currentMotion.End(); } _currentMotion = new ZoomMotion(Camera.transform, transform, _originalOffset, scale, duration); _motions.Clear(); }
public void Rotate(float angle, float duration) { if (_currentMotion != null && !(_currentMotion is RotateMotion)) { _currentMotion.End(); } _currentMotion = new RotateMotion(transform, angle, duration); _motions.Clear(); }
private void Awake() { _targetModelObject = transform.FindChild("Target Model").gameObject; _targetModelObject.SetActive(false); _motionController = GetComponent<Motion>(); ResetLaunchTimer(); }
public void Pan(Point point, float duration) { Vector3 end = _theme.PointToVector3(point); if (_currentMotion != null && !(_currentMotion is PanMotion)) { _currentMotion.End(); } _currentMotion = new PanMotion(transform, end, duration); _motions.Clear(); }
/// <summary> /// 玩家腳色播放動作,傳入動作類型與是否錯開播放 /// </summary> public static void SetPlayerCharaMotion(Motion _motion, bool _stagger) { for (int i = 0; i < PCharaList.Count; i++) { if (_stagger) PCharaList[i].PlayMotion(_motion, ((float)i * 2f) / 10f); else PCharaList[i].PlayMotion(_motion, 0); } }
public MotionSensor(TimeSpan updateInterval) { if (this.IsSupported) { this.sensor = new Motion() { TimeBetweenUpdates = updateInterval }; } }
public PlayerRenderContext(PlayerContext playerContext, Motion motion) { this.Name = playerContext.Name; this.Number = playerContext.Number; this.Score = playerContext.Score; this.Motion = motion; this.LastPos = playerContext.LastPos; this.Power = playerContext.Power; this.Stun = playerContext.Stun; }
protected override Motion GetNextMotion(int index) { Motion m = new Motion(); m.Axis = new Vector3D(0, 1, 0); m.X = Owner.FrontItemGap + Owner.ItemGap * (index - Owner.SelectedIndex) + Owner.XOffset; m.Z = -1 * Owner.ItemGap * (index - Owner.SelectedIndex) + Owner.ZOffset; m.Y = Owner.YOffset; ChangeStateForElement(index, Visibility.Collapsed); return m; }
// Constructor public MainPage() { InitializeComponent(); if (Motion.IsSupported) { sensor = new Motion(); sensor.TimeBetweenUpdates = TimeSpan.FromMilliseconds(66); sensor.CurrentValueChanged += sensor_CurrentValueChanged; sensor.Calibrate += sensor_Calibrate; } }
bool m_actionSoundEnable; //액션의 효과음이 유효하면 true. (대미지 시는 서로 OFF로 되어 있을 것). void Awake() { GetComponent<AudioSource>().clip = m_landingSE; GetComponent<AudioSource>().PlayDelayed(0.2f); //착지음을 늦게 재생시킨다. m_currentMotion = Motion.In; m_anim = GetComponentInChildren<Animation>(); m_rps = RPSKind.None; m_opponentRps = RPSKind.None; m_damage = 0; m_actionEffectEnable = false; m_actionSoundEnable = false; }
private void Awake() { Transform planeTransform = transform.FindChild("Plane"); _modelTransform = planeTransform.FindChild("Plane Model"); _modelObject = _modelTransform.gameObject; _motionController = planeTransform.GetComponent<Motion>(); _collisionController = planeTransform.GetComponent<Collisions>(); _chaseCameraController = transform.FindChild("Camera").GetComponent<ChaseCamera>(); _statusManager = transform.FindChild("Status Manager").GetComponent<StatusDisplayManager>(); }
/// <summary> /// 播放腳色施法 /// </summary> public void PlayMotion(Motion _motion, float _normalizedTime) { switch (_motion) { case Motion.Stay: if (Animator.StringToHash(string.Format("Base Layer.{0}", Motion.Stay.ToString())) != Ani_Chara.GetCurrentAnimatorStateInfo(0).fullPathHash) Ani_Chara.SetTrigger(Motion.Stay.ToString()); break; case Motion.GoForward: if (Animator.StringToHash(string.Format("Base Layer.{0}", Motion.GoForward.ToString())) != Ani_Chara.GetCurrentAnimatorStateInfo(0).fullPathHash) Ani_Chara.Play(Motion.GoForward.ToString(), 0, _normalizedTime); break; case Motion.Attack: Ani_Chara.SetBool("InFighting", FightScene.Fight); FightScene.SetAction(true);//設定有人在執行動作 if (Animator.StringToHash(string.Format("Base Layer.{0}", Motion.Attack.ToString())) != Ani_Chara.GetCurrentAnimatorStateInfo(0).fullPathHash) { Ani_Chara.Play(Motion.Attack.ToString(), 0, _normalizedTime); } else { //重播 Ani_Chara.StopPlayback(); } break; case Motion.Beaten: if (Animator.StringToHash(string.Format("Base Layer.{0}", Motion.Beaten.ToString())) != Ani_Chara.GetCurrentAnimatorStateInfo(0).fullPathHash) Ani_Chara.Play(Motion.Beaten.ToString(), 0, _normalizedTime); else { //重播 Ani_Chara.StopPlayback(); } break; case Motion.Support: FightScene.SetAction(true);//設定有人在執行動作 Ani_Chara.SetBool("InFighting", FightScene.Fight); if (Animator.StringToHash(string.Format("Base Layer.{0}", Motion.Support.ToString())) != Ani_Chara.GetCurrentAnimatorStateInfo(0).fullPathHash) Ani_Chara.Play(Motion.Support.ToString(), 0, _normalizedTime); else { //重播 Ani_Chara.StopPlayback(); } break; case Motion.Die: if (Animator.StringToHash(string.Format("Base Layer.{0}", Motion.Die.ToString())) != Ani_Chara.GetCurrentAnimatorStateInfo(0).fullPathHash) Ani_Chara.Play(Motion.Die.ToString(), 0, _normalizedTime); break; } }
private void PrepareStoryboard(Storyboard sb, Motion motion) { // Child animations AxisAngleRotation3D rotation = (sb.Children[0] as Rotation3DAnimation).To as AxisAngleRotation3D; DoubleAnimation xAnim = sb.Children[1] as DoubleAnimation; DoubleAnimation yAnim = sb.Children[2] as DoubleAnimation; DoubleAnimation zAnim = sb.Children[3] as DoubleAnimation; rotation.Angle = motion.Angle; rotation.Axis = motion.Axis; xAnim.To = motion.X; yAnim.To = motion.Y; zAnim.To = motion.Z; }
public MotionSamplePage() { InitializeComponent(); Loaded += (s, e) => { if (Motion.IsSupported) { _m = new Motion(); _m.CurrentValueChanged += MotionCurrentValueChanged; _m.Start(); } }; }
public void SetTile(State state, Motion motion, Vector2 position, Texture2D tileSheet, Rectangle tileArea) { this.state = state; this.motion = motion; this.position = position; increase = true; tileImage = CropImage(tileSheet, tileArea); range = 50; counter = 0; moveSpeed = 100f; animation = new Animation(); animation.LoadContent(ScreenManager.Instance.Content, tileImage, "", position); }
// Constructor public MainPage() { InitializeComponent(); // Sample code to localize the ApplicationBar //BuildLocalizedApplicationBar(); if (Motion.IsSupported) { sensor = new Motion(); sensor.TimeBetweenUpdates = TimeSpan.FromMilliseconds(66); sensor.CurrentValueChanged += sensor_CurrentValueChanged; sensor.Calibrate += sensor_Calibrate; } }
public void Move(Motion command) { if (Position == null) { throw new InvalidOperationException("Start Position Not Set!"); } if (Motion.Left == command || Motion.Right == command) { _moveCommands[FindCommandIndexForCommand(command)].Invoke(false); } else { _moveCommands[FindCommandIndexForCommand(command)].Invoke(true); } }
public PhoneOrientation() { values = new float[3]; motion = new Motion(); motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged); // Try to start the Motion API. try { motion.Start(); } catch (Exception e) { MessageBox.Show("unable to start the Motion API."); } }
public void SetTile(State state, Motion motion, Vector2 position, Texture2D tileSheet, Rectangle tileArea, string text) { this.state = state; this.motion = motion; this.position = position; increase = true; tileImage = CropImage(tileSheet, tileArea); range = 90; counter = 0; moveSpeed = 80f; animation = new Animation(); animation.LoadContent(ScreenManager.Instance.Content, tileImage, text, position, Color.White); containsEntity = false; velocity = Vector2.Zero; }
public static void PostMotion(Motion motion) { var reddit = GetReddit(); var subreddit = reddit.GetSubreddit(Config.RedditSubreddit); Post post; if (motion.PostUrl != "") { post = reddit.GetPost(new Uri(motion.PostUrl)); post.EditText(motion.ToRedditMarkdown()); } else { post = subreddit.SubmitTextPost("[" + motion.Id + "] " + motion.Text, motion.ToRedditMarkdown()); } post.Save(); motion.PostUrl = post.Url.AbsoluteUri; }
public static int InsertMotion(Motion motion) { var result = -1; using (var db = CreateConnection()) using (var sql = db.CreateCommand()) { db.Open(); sql.CommandText = @"INSERT INTO motion (createDt,moderatorId,text,status,redditLink,isInOrder) VALUES (DATE('now'),@sponsor,@text,@status,@redditLink,@isInOrder);"; var p0 = sql.CreateParameter(); p0.ParameterName = "@sponsor"; p0.Value = motion.Sponsor.Id; sql.Parameters.Add(p0); var p1 = sql.CreateParameter(); p1.ParameterName = "@text"; p1.Value = motion.Text; sql.Parameters.Add(p1); var p2 = sql.CreateParameter(); p2.ParameterName = "@status"; p2.Value = (int)motion.Status; sql.Parameters.Add(p2); var p3 = sql.CreateParameter(); p3.ParameterName = "@redditLink"; p3.Value = motion.PostUrl; sql.Parameters.Add(p3); var p4 = sql.CreateParameter(); p4.ParameterName = "@isInOrder"; p4.Value = 0; sql.Parameters.Add(p4); sql.Prepare(); sql.ExecuteNonQuery(); sql.CommandText = "SELECT last_insert_rowid()"; result = Int32.Parse(sql.ExecuteScalar().ToString()); sql.ExecuteNonQuery(); db.Close(); } return result; }
private AnimatorState CreateDualBlendState(Motion clip, Motion resting, Vector3 position, Motion posingLeft, Motion posingRight) { var clipName = UnshimName(clip.name) + " Dual " + UnshimName(resting.name); var newState = _machine.AddState(SanitizeName(clipName), position); newState.motion = CreateDualBlendTree(resting, clip, posingLeft, posingRight, clipName, _animatorController, _useGestureWeightCorrection, _useSmoothing); newState.writeDefaultValues = _writeDefaultsForFaceExpressions; return(newState); }
public static BotPosition[] Move(BotPosition bot, Motion motion, Turn turn) { return(BotPosition.Move(bot, motion, turn, 1)); }
protected MotorBase(Motion motion) { Motion = motion; Motion.RegisterMotor(this); }
/// <summary> /// Метод, вызывающий событие <see cref="ArrowPressed"/> /// </summary> /// <param name="args">Аргументы события</param> protected virtual void OnArrowPressed(MotionVectorEventArgs args) => Motion?.Invoke(this, args);
public override void Dispose() { Motion.UnregisterMotor(this); }
private void CreateController() { if (this.m_Controller == null && this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null && this.m_RefTransition != null) { this.m_LayerIndex = 0; this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.AddLayer("preview"); bool flag = true; if (this.m_LayerMask != null) { AvatarMaskBodyPart avatarMaskBodyPart = AvatarMaskBodyPart.Root; while (avatarMaskBodyPart < AvatarMaskBodyPart.LastBodyPart && flag) { if (!this.m_LayerMask.GetHumanoidBodyPartActive(avatarMaskBodyPart)) { flag = false; } avatarMaskBodyPart++; } if (!flag) { this.m_Controller.AddLayer("Additionnal"); this.m_LayerIndex++; AnimatorControllerLayer[] layers = this.m_Controller.layers; layers[this.m_LayerIndex].avatarMask = this.m_LayerMask; this.m_Controller.layers = layers; } } this.m_StateMachine = this.m_Controller.layers[this.m_LayerIndex].stateMachine; this.m_StateMachine.pushUndo = false; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; this.m_SrcMotion = this.m_RefSrcState.motion; this.m_DstMotion = this.m_RefDstState.motion; this.m_ParameterMinMax.Clear(); if (this.m_SrcMotion && this.m_SrcMotion is BlendTree) { BlendTree blendTree = this.m_SrcMotion as BlendTree; for (int i = 0; i < blendTree.recursiveBlendParameterCount; i++) { string recursiveBlendParameter = blendTree.GetRecursiveBlendParameter(i); if (this.m_Controller.IndexOfParameter(recursiveBlendParameter) == -1) { this.m_Controller.AddParameter(recursiveBlendParameter, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(blendTree.GetRecursiveBlendParameterMin(i), blendTree.GetRecursiveBlendParameterMax(i))); } } } if (this.m_DstMotion && this.m_DstMotion is BlendTree) { BlendTree blendTree2 = this.m_DstMotion as BlendTree; for (int j = 0; j < blendTree2.recursiveBlendParameterCount; j++) { string recursiveBlendParameter2 = blendTree2.GetRecursiveBlendParameter(j); int num = this.m_Controller.IndexOfParameter(recursiveBlendParameter2); if (num == -1) { this.m_Controller.AddParameter(recursiveBlendParameter2, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(blendTree2.GetRecursiveBlendParameterMin(j), blendTree2.GetRecursiveBlendParameterMax(j))); } else { this.m_ParameterMinMax[num] = new Vector2(Mathf.Min(blendTree2.GetRecursiveBlendParameterMin(j), this.m_ParameterMinMax[num][0]), Mathf.Max(blendTree2.GetRecursiveBlendParameterMax(j), this.m_ParameterMinMax[num][1])); } } } this.m_SrcState = this.m_StateMachine.AddState(this.m_RefSrcState.name); this.m_SrcState.pushUndo = false; this.m_SrcState.hideFlags = HideFlags.HideAndDontSave; this.m_DstState = this.m_StateMachine.AddState(this.m_RefDstState.name); this.m_DstState.pushUndo = false; this.m_DstState.hideFlags = HideFlags.HideAndDontSave; this.CopyStateForPreview(this.m_RefSrcState, ref this.m_SrcState); this.CopyStateForPreview(this.m_RefDstState, ref this.m_DstState); this.m_Transition = this.m_SrcState.AddTransition(this.m_DstState, true); this.m_Transition.pushUndo = false; this.m_Transition.hideFlags = HideFlags.DontSave; this.CopyTransitionForPreview(this.m_RefTransition, ref this.m_Transition); this.DisableIKOnFeetIfNeeded(); AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); AnimatorController expr_404 = this.m_Controller; expr_404.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_404.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); } }
public AvatarPreview(Animator previewObjectInScene, Motion objectOnSameAsset) { this.InitInstance(previewObjectInScene, objectOnSameAsset); }
private void ResampleTransition(AnimatorStateTransition transition, AvatarMask layerMask, TransitionPreview.TransitionInfo info, Animator previewObject) { this.m_IsResampling = true; this.m_MustResample = false; this.m_ValidTransition = true; bool flag = this.m_RefTransition != transition; this.m_RefTransition = transition; this.m_RefTransitionInfo = info; this.m_LayerMask = layerMask; if (this.m_AvatarPreview != null) { this.m_AvatarPreview.OnDestroy(); this.m_AvatarPreview = null; } this.ClearController(); Motion motion = this.m_RefSrcState.motion; this.Init(previewObject, (!(motion != null)) ? this.m_RefDstState.motion : motion); if (this.m_Controller == null) { this.m_IsResampling = false; } else { this.m_AvatarPreview.Animator.allowConstantClipSamplingOptimization = false; this.m_StateMachine.defaultState = this.m_DstState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-05f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); float length = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex).length; this.m_StateMachine.defaultState = this.m_SrcState; this.m_Transition.mute = false; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-05f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); float length2 = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex).length; if (this.m_LayerIndex > 0) { this.m_AvatarPreview.Animator.stabilizeFeet = false; } float num = length2 * this.m_RefTransition.exitTime + this.m_Transition.duration * ((!this.m_RefTransition.hasFixedDuration) ? length2 : 1f) + length; if (num > 2000f) { Debug.LogWarning("Transition duration is longer than 2000 second, Disabling previewer."); this.m_ValidTransition = false; this.m_IsResampling = false; } else { float num2 = (this.m_RefTransition.exitTime <= 0f) ? length2 : (length2 * this.m_RefTransition.exitTime); float num3 = (num2 <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(num2 / 300f, 0.0333333351f), num2 / 5f); float num4 = (length <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length / 300f, 0.0333333351f), length / 5f); num3 = Mathf.Max(num3, num / 600f); num4 = Mathf.Max(num4, num / 600f); float num5 = num3; float num6 = 0f; bool flag2 = false; bool flag3 = false; bool flag4 = false; this.m_AvatarPreview.Animator.StartRecording(-1); this.m_LeftStateWeightA = 0f; this.m_LeftStateTimeA = 0f; this.m_AvatarPreview.Animator.Update(0f); while (!flag4 && num6 < num) { this.m_AvatarPreview.Animator.Update(num5); AnimatorStateInfo currentAnimatorStateInfo = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex); num6 += num5; if (!flag2) { this.m_LeftStateWeightA = (this.m_LeftStateWeightB = currentAnimatorStateInfo.normalizedTime); this.m_LeftStateTimeA = (this.m_LeftStateTimeB = num6); flag2 = true; } if (flag3 && num6 >= num) { flag4 = true; } if (!flag3 && currentAnimatorStateInfo.IsName(this.m_DstState.name)) { this.m_RightStateWeightA = currentAnimatorStateInfo.normalizedTime; this.m_RightStateTimeA = num6; flag3 = true; } if (!flag3) { this.m_LeftStateWeightB = currentAnimatorStateInfo.normalizedTime; this.m_LeftStateTimeB = num6; } if (flag3) { this.m_RightStateWeightB = currentAnimatorStateInfo.normalizedTime; this.m_RightStateTimeB = num6; } if (this.m_AvatarPreview.Animator.IsInTransition(this.m_LayerIndex)) { num5 = num4; } } float stopTime = num6; this.m_AvatarPreview.Animator.StopRecording(); if (Mathf.Approximately(this.m_LeftStateWeightB, this.m_LeftStateWeightA) || Mathf.Approximately(this.m_RightStateWeightB, this.m_RightStateWeightA)) { Debug.LogWarning("Difference in effective length between states is too big. Transition preview will be disabled."); this.m_ValidTransition = false; this.m_IsResampling = false; } else { float num7 = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); float num8 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); if (this.m_MustSampleMotions) { this.m_MustSampleMotions = false; this.m_SrcPivotList.Clear(); this.m_DstPivotList.Clear(); num5 = num4; this.m_StateMachine.defaultState = this.m_DstState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(0f); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); for (num6 = 0f; num6 <= num8; num6 += num5 * 2f) { Timeline.PivotSample pivotSample = new Timeline.PivotSample(); pivotSample.m_Time = num6; pivotSample.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; this.m_DstPivotList.Add(pivotSample); this.m_AvatarPreview.Animator.Update(num5 * 2f); } num5 = num3; this.m_StateMachine.defaultState = this.m_SrcState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); for (num6 = 0f; num6 <= num7; num6 += num5 * 2f) { Timeline.PivotSample pivotSample2 = new Timeline.PivotSample(); pivotSample2.m_Time = num6; pivotSample2.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; this.m_SrcPivotList.Add(pivotSample2); this.m_AvatarPreview.Animator.Update(num5 * 2f); } this.m_Transition.mute = false; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); } this.m_Timeline.StopTime = (this.m_AvatarPreview.timeControl.stopTime = stopTime); this.m_AvatarPreview.timeControl.currentTime = this.m_Timeline.Time; if (flag) { Timeline arg_7DB_0 = this.m_Timeline; float num9 = this.m_AvatarPreview.timeControl.currentTime = (this.m_AvatarPreview.timeControl.startTime = 0f); this.m_Timeline.StartTime = num9; arg_7DB_0.Time = num9; this.m_Timeline.ResetRange(); } this.m_AvatarPreview.Animator.StartPlayback(); this.m_IsResampling = false; } } } }
/// <summary> /// <para>Sets the effective Motion for the AnimatorState. The Motion is either stored in the AnimatorStateMachine or in the AnimatorLayer's ovverrides. Use this function to set the Motion that is effectively used.</para> /// </summary> /// <param name="state">The AnimatorState which we want to set the Motion.</param> /// <param name="motion">The Motion that will be set.</param> /// <param name="layerIndex">The layer to set the Motion.</param> public void SetStateEffectiveMotion(AnimatorState state, Motion motion) { this.SetStateEffectiveMotion(state, motion, 0); }
/// <summary> /// <para>Utility function that creates a new state with the motion in it.</para> /// </summary> /// <param name="motion">The Motion that will be in the AnimatorState.</param> /// <param name="layerIndex">The layer where the Motion will be added.</param> public AnimatorState AddMotion(Motion motion) => this.AddMotion(motion, 0);
public override bool AbsMove(int nAxisNo, double nPos, double nSpeed) { if (m_Axishand == null || m_Axishand[nAxisNo] == null) { return(false); } uint Result = 0; double speed = nSpeed; double Acc = m_MovePrm[nAxisNo].AccH; double Dcc = m_MovePrm[nAxisNo].DccH; switch (nSpeed) { case (double)0: Acc = m_MovePrm[nAxisNo].AccH; Dcc = m_MovePrm[nAxisNo].DccH; speed = m_MovePrm[nAxisNo].VelH; break; case (double)SpeedType.Mid: Acc = m_MovePrm[nAxisNo].AccM; Dcc = m_MovePrm[nAxisNo].DccM; speed = m_MovePrm[nAxisNo].VelM; break; case (double)SpeedType.Low: Acc = m_MovePrm[nAxisNo].AccL; Dcc = m_MovePrm[nAxisNo].DccL; speed = m_MovePrm[nAxisNo].VelL; break; } Result |= Motion.mAcm_SetF64Property(m_Axishand[nAxisNo], (uint)PropertyID.PAR_AxVelLow, 0.0 * speed); if (Result != (uint)ErrorCode.SUCCESS) { return(false); } Result |= Motion.mAcm_SetF64Property(m_Axishand[nAxisNo], (uint)PropertyID.PAR_AxVelHigh, speed); if (Result != (uint)ErrorCode.SUCCESS) { return(false); } Result |= Motion.mAcm_SetF64Property(m_Axishand[nAxisNo], (uint)PropertyID.PAR_AxAcc, Acc); if (Result != (uint)ErrorCode.SUCCESS) { return(false); } Result |= Motion.mAcm_SetF64Property(m_Axishand[nAxisNo], (uint)PropertyID.PAR_AxDec, Dcc); if (Result != (uint)ErrorCode.SUCCESS) { return(false); } double AxJerk = 0; Result |= Motion.mAcm_SetF64Property(m_Axishand[nAxisNo], (uint)PropertyID.PAR_AxJerk, AxJerk); if (Result != (uint)ErrorCode.SUCCESS) { return(false); } Result |= Motion.mAcm_AxResetError(m_Axishand[nAxisNo]); Result |= Motion.mAcm_AxMoveAbs(m_Axishand[nAxisNo], nPos); return(Result == (uint)ErrorCode.SUCCESS); }
private void button3_Click(object sender, EventArgs e) { Motion.Axis(X).ZeroPos(); Motion.Axis(Y).ZeroPos(); }
private AnimatorState CreateSidedBlendState(Motion squeezing, Vector3 offset, Motion resting, Vector3 gridPosition, bool isLeftSide) { var clipName = UnshimName(squeezing.name) + " " + (isLeftSide ? "BlendLeft" : "BlendRight") + " " + UnshimName(resting.name); var newState = _machine.AddState(SanitizeName(clipName), offset + gridPosition); newState.motion = CreateBlendTree( resting, squeezing, isLeftSide ? LeftParam(_useGestureWeightCorrection, _useSmoothing) : RightParam(_useGestureWeightCorrection, _useSmoothing), clipName, _animatorController); newState.writeDefaultValues = _writeDefaultsForFaceExpressions; return(newState); }
void CheckResources() { ActiveTextures.Clear(); ActiveMaterials.Clear(); ActiveMeshDetails.Clear(); Renderer[] renderers = FindObjects <Renderer>(); //Debug.Log("Total renderers "+renderers.Length); foreach (Renderer renderer in renderers) { //Debug.Log("Renderer is "+renderer.name); foreach (Material material in renderer.sharedMaterials) { MaterialDetails tMaterialDetails = FindMaterialDetails(material); if (tMaterialDetails == null) { tMaterialDetails = new MaterialDetails(); tMaterialDetails.material = material; ActiveMaterials.Add(tMaterialDetails); } tMaterialDetails.FoundInRenderers.Add(renderer); } if (renderer is SpriteRenderer) { SpriteRenderer tSpriteRenderer = (SpriteRenderer)renderer; if (tSpriteRenderer.sprite != null) { var tSpriteTextureDetail = GetTextureDetail(tSpriteRenderer.sprite.texture, renderer); if (!ActiveTextures.Contains(tSpriteTextureDetail)) { ActiveTextures.Add(tSpriteTextureDetail); } } } } if (IncludeGuiElements) { Graphic[] graphics = FindObjects <Graphic>(); foreach (Graphic graphic in graphics) { if (graphic.mainTexture) { var tSpriteTextureDetail = GetTextureDetail(graphic.mainTexture, graphic); if (!ActiveTextures.Contains(tSpriteTextureDetail)) { ActiveTextures.Add(tSpriteTextureDetail); } } if (graphic.materialForRendering) { MaterialDetails tMaterialDetails = FindMaterialDetails(graphic.materialForRendering); if (tMaterialDetails == null) { tMaterialDetails = new MaterialDetails(); tMaterialDetails.material = graphic.materialForRendering; ActiveMaterials.Add(tMaterialDetails); } tMaterialDetails.FoundInGraphics.Add(graphic); } } } foreach (MaterialDetails tMaterialDetails in ActiveMaterials) { Material tMaterial = tMaterialDetails.material; if (tMaterial != null) { var dependencies = EditorUtility.CollectDependencies(new UnityEngine.Object[] { tMaterial }); foreach (Object obj in dependencies) { if (obj is Texture) { Texture tTexture = obj as Texture; var tTextureDetail = GetTextureDetail(tTexture, tMaterial, tMaterialDetails); if (!ActiveTextures.Contains(tTextureDetail)) { ActiveTextures.Add(tTextureDetail); } } } //if the texture was downloaded, it won't be included in the editor dependencies if (tMaterial.mainTexture != null && !dependencies.Contains(tMaterial.mainTexture)) { var tTextureDetail = GetTextureDetail(tMaterial.mainTexture, tMaterial, tMaterialDetails); if (!ActiveTextures.Contains(tTextureDetail)) { ActiveTextures.Add(tTextureDetail); } } } } MeshFilter[] meshFilters = FindObjects <MeshFilter>(); foreach (MeshFilter tMeshFilter in meshFilters) { Mesh tMesh = tMeshFilter.sharedMesh; if (tMesh != null) { MeshDetails tMeshDetails = FindMeshDetails(tMesh); if (tMeshDetails == null) { tMeshDetails = new MeshDetails(); tMeshDetails.mesh = tMesh; ActiveMeshDetails.Add(tMeshDetails); } tMeshDetails.FoundInMeshFilters.Add(tMeshFilter); } } SkinnedMeshRenderer[] skinnedMeshRenderers = FindObjects <SkinnedMeshRenderer>(); foreach (SkinnedMeshRenderer tSkinnedMeshRenderer in skinnedMeshRenderers) { Mesh tMesh = tSkinnedMeshRenderer.sharedMesh; if (tMesh != null) { MeshDetails tMeshDetails = FindMeshDetails(tMesh); if (tMeshDetails == null) { tMeshDetails = new MeshDetails(); tMeshDetails.mesh = tMesh; ActiveMeshDetails.Add(tMeshDetails); } tMeshDetails.FoundInSkinnedMeshRenderer.Add(tSkinnedMeshRenderer); } } if (IncludeSpriteAnimations) { Animator[] animators = FindObjects <Animator>(); foreach (Animator anim in animators) { #if UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 UnityEditorInternal.AnimatorController ac = anim.runtimeAnimatorController as UnityEditorInternal.AnimatorController; #elif UNITY_5 UnityEditor.Animations.AnimatorController ac = anim.runtimeAnimatorController as UnityEditor.Animations.AnimatorController; #endif //Skip animators without layers, this can happen if they don't have an animator controller. if (!ac || ac.layers == null || ac.layers.Length == 0) { continue; } for (int x = 0; x < anim.layerCount; x++) { #if UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 UnityEditorInternal.StateMachine sm = ac.GetLayer(x).stateMachine; int cnt = sm.stateCount; #elif UNITY_5 UnityEditor.Animations.AnimatorStateMachine sm = ac.layers[x].stateMachine; int cnt = sm.states.Length; #endif for (int i = 0; i < cnt; i++) { #if UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 UnityEditorInternal.State state = sm.GetState(i); Motion m = state.GetMotion(); #elif UNITY_5 UnityEditor.Animations.AnimatorState state = sm.states[i].state; Motion m = state.motion; #endif if (m != null) { AnimationClip clip = m as AnimationClip; EditorCurveBinding[] ecbs = AnimationUtility.GetObjectReferenceCurveBindings(clip); foreach (EditorCurveBinding ecb in ecbs) { if (ecb.propertyName == "m_Sprite") { foreach (ObjectReferenceKeyframe keyframe in AnimationUtility.GetObjectReferenceCurve(clip, ecb)) { Sprite tSprite = keyframe.value as Sprite; if (tSprite != null) { var tTextureDetail = GetTextureDetail(tSprite.texture, anim); if (!ActiveTextures.Contains(tTextureDetail)) { ActiveTextures.Add(tTextureDetail); } } } } } } } } } } if (IncludeScriptReferences) { MonoBehaviour[] scripts = FindObjects <MonoBehaviour>(); foreach (MonoBehaviour script in scripts) { BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; // only public non-static fields are bound to by Unity. FieldInfo[] fields = script.GetType().GetFields(flags); foreach (FieldInfo field in fields) { System.Type fieldType = field.FieldType; if (fieldType == typeof(Sprite)) { Sprite tSprite = field.GetValue(script) as Sprite; if (tSprite != null) { var tSpriteTextureDetail = GetTextureDetail(tSprite.texture, script); if (!ActiveTextures.Contains(tSpriteTextureDetail)) { ActiveTextures.Add(tSpriteTextureDetail); } } } } } } TotalTextureMemory = 0; foreach (TextureDetails tTextureDetails in ActiveTextures) { TotalTextureMemory += tTextureDetails.memSizeKB; } TotalMeshVertices = 0; foreach (MeshDetails tMeshDetails in ActiveMeshDetails) { TotalMeshVertices += tMeshDetails.mesh.vertexCount; } // Sort by size, descending ActiveTextures.Sort(delegate(TextureDetails details1, TextureDetails details2) { return(String.Compare(details1.name, details2.name, StringComparison.Ordinal)); }); ActiveMeshDetails.Sort(delegate(MeshDetails details1, MeshDetails details2) { return(details2.mesh.name.CompareTo(details1.mesh.name)); }); collectedInPlayingMode = Application.isPlaying; }
private static GameObject CalculatePreviewGameObject(Animator selectedAnimator, Motion motion, ModelImporterAnimationType animationType) { AnimationClip firstAnimationClipFromMotion = AvatarPreview.GetFirstAnimationClipFromMotion(motion); GameObject gameObject = AvatarPreviewSelection.GetPreview(animationType); GameObject result; if (AvatarPreview.IsValidPreviewGameObject(gameObject, ModelImporterAnimationType.None)) { result = gameObject; } else if (selectedAnimator != null && AvatarPreview.IsValidPreviewGameObject(selectedAnimator.gameObject, animationType)) { result = selectedAnimator.gameObject; } else { gameObject = AvatarPreview.FindBestFittingRenderableGameObjectFromModelAsset(firstAnimationClipFromMotion, animationType); if (gameObject != null) { result = gameObject; } else if (animationType == ModelImporterAnimationType.Human) { result = AvatarPreview.GetHumanoidFallback(); } else if (animationType == ModelImporterAnimationType.Generic) { result = AvatarPreview.GetGenericAnimationFallback(); } else { result = null; } } return(result); }
public int HandleState(ref AnimatorState state) { bool stateExist; var stateInfo = controllerInfo.states.AddObject(state, out stateExist); if (!stateExist) { stateInfo.Value.AddField("name", state.name); var stateJSON = stateInfo.Value; JSONObject stateTransitions = new JSONObject(JSONObject.Type.ARRAY); for (int j = 0; j < state.transitions.Length; j++) { AnimatorStateTransition trans = state.transitions[j]; stateTransitions.Add(HandleStateTransition(state.name, ref trans)); } stateJSON.AddField("transitions", stateTransitions); // animationClip Motion motion = state.motion; if (motion == null) { stateJSON.AddField("motion", new JSONObject(JSONObject.Type.NULL)); } else if (motion.GetType() == typeof(AnimationClip)) { JSONObject clipJSON = new JSONObject(JSONObject.Type.OBJECT); AnimationClip clip = motion as AnimationClip; if (handleBeforeAnimationClip != null && !handleBeforeAnimationClip(clip, state, gameObject)) { // 如果return false,说明这个animationclip被外面所接管 clipJSON.AddField("id", ""); } else { string clipUid = HandleAnimationClip(ref clip); clipJSON.AddField("id", clipUid); } clipJSON.AddField("type", "AnimationClip"); stateJSON.AddField("motion", clipJSON); } else if (motion.GetType() == typeof(BlendTree)) { JSONObject btJSON = new JSONObject(JSONObject.Type.OBJECT); BlendTree bt = motion as BlendTree; btJSON.AddField("type", "BlendTree"); btJSON.AddField("id", TraverseBlendTree(ref bt)); stateJSON.AddField("motion", btJSON); } stateJSON.AddField("cycleOffset", state.cycleOffset); if (state.cycleOffsetParameterActive) { stateJSON.AddField("cycleOffsetParameter", state.cycleOffsetParameter); } else { stateJSON.AddField("cycleOffsetParameter", new JSONObject(JSONObject.Type.NULL)); } stateJSON.AddField("mirror", state.mirror); if (state.mirrorParameterActive) { stateJSON.AddField("mirrorParameter", state.mirrorParameter); } else { stateJSON.AddField("mirrorParameter", new JSONObject(JSONObject.Type.NULL)); } stateInfo.Value.AddField("speed", state.speed); if (state.speedParameterActive) { stateJSON.AddField("speedParameter", state.speedParameter); } else { stateJSON.AddField("speedParameter", new JSONObject(JSONObject.Type.NULL)); } #if UNITY_2017_1_OR_NEWER if (state.timeParameterActive) { stateJSON.AddField("timeParameter", state.timeParameter); } else { #endif stateJSON.AddField("timeParameter", new JSONObject(JSONObject.Type.NULL)); #if UNITY_2017_1_OR_NEWER } #endif return(stateInfo.Key); } else { return(stateInfo.Key); } }
private void ForAnalog(List <TransitionCondition> transitionConditions, Motion squeezing, Motion resting, HandSide handSide) { AnimatorState blendState = null; foreach (var transitionCondition in transitionConditions) { var nullableTransition = GetNullableStageValue(transitionCondition); if (blendState == null) { Vector3 offset = ToPotentialGridPosition(transitionCondition); blendState = CreateSidedBlendState(squeezing, offset, resting, Vector3.zero, handSide == HandSide.LeftHand); } CreateTransition(nullableTransition, transitionCondition.Permutation, blendState, transitionCondition.TransitionDuration); } }
/// <summary> /// Broadcasts the player death animation, updates vitae, and sends network messages for player death /// Queues the action to call TeleportOnDeath and enter portal space soon /// </summary> protected override void Die(DamageHistoryInfo lastDamager, DamageHistoryInfo topDamager) { IsInDeathProcess = true; if (topDamager?.Guid == Guid && IsPKType) { var topDamagerOther = DamageHistory.GetTopDamager(false); if (topDamagerOther != null && topDamagerOther.IsPlayer) { topDamager = topDamagerOther; } } UpdateVital(Health, 0); NumDeaths++; suicideInProgress = false; if (CombatMode == CombatMode.Magic && MagicState.IsCasting) { FailCast(false); } // TODO: instead of setting IsBusy here, // eventually all of the places that check for states such as IsBusy || Teleporting // might want to use a common function, and IsDead should return a separate error IsBusy = true; // killer = top damager for looting rights if (topDamager != null) { KillerId = topDamager.Guid.Full; } // broadcast death animation var deathAnim = new Motion(MotionStance.NonCombat, MotionCommand.Dead); EnqueueBroadcastMotion(deathAnim); // create network messages for player death var msgHealthUpdate = new GameMessagePrivateUpdateAttribute2ndLevel(this, Vital.Health, 0); // TODO: death sounds? seems to play automatically in client // var msgDeathSound = new GameMessageSound(Guid, Sound.Death1, 1.0f); var msgNumDeaths = new GameMessagePrivateUpdatePropertyInt(this, PropertyInt.NumDeaths, NumDeaths); // send network messages for player death Session.Network.EnqueueSend(msgHealthUpdate, msgNumDeaths); if (lastDamager?.Guid == Guid) // suicide { var msgSelfInflictedDeath = new GameEventWeenieError(Session, WeenieError.YouKilledYourself); Session.Network.EnqueueSend(msgSelfInflictedDeath); } // update vitae // players who died in a PKLite fight do not accrue vitae if (!IsPKLiteDeath(topDamager)) { InflictVitaePenalty(); } if (IsPKDeath(topDamager) || AugmentationSpellsRemainPastDeath == 0) { var msgPurgeEnchantments = new GameEventMagicPurgeEnchantments(Session); EnchantmentManager.RemoveAllEnchantments(); Session.Network.EnqueueSend(msgPurgeEnchantments); } else { Session.Network.EnqueueSend(new GameMessageSystemChat("Your augmentation prevents the tides of death from ripping away your current enchantments!", ChatMessageType.Broadcast)); } // wait for the death animation to finish var dieChain = new ActionChain(); var animLength = DatManager.PortalDat.ReadFromDat <MotionTable>(MotionTableId).GetAnimationLength(MotionCommand.Dead); dieChain.AddDelaySeconds(animLength + 1.0f); dieChain.AddAction(this, () => { CreateCorpse(topDamager); ThreadSafeTeleportOnDeath(); // enter portal space if (IsPKDeath(topDamager) || IsPKLiteDeath(topDamager)) { SetMinimumTimeSincePK(); } IsBusy = false; }); dieChain.EnqueueChain(); }
public int TraverseBlendTree(ref BlendTree tree) { bool treeExist; var treeInfo = controllerInfo.blendTrees.AddObject(tree, out treeExist); if (treeExist) { return(treeInfo.Key); } var json = treeInfo.Value; json.AddField("name", tree.name); var childrenJSON = new JSONObject(JSONObject.Type.ARRAY); json.AddField("children", childrenJSON); ChildMotion[] children = tree.children; for (int i = 0; i < children.Length; i++) { var childJSON = new JSONObject(JSONObject.Type.OBJECT); childrenJSON.Add(childJSON); var motionJSON = new JSONObject(JSONObject.Type.OBJECT); Motion motion = children[i].motion; if (motion.GetType() == typeof(AnimationClip)) { AnimationClip clip = motion as AnimationClip; motionJSON.AddField("type", "AnimationClip"); motionJSON.AddField("id", HandleAnimationClip(ref clip)); } else if (motion.GetType() == typeof(BlendTree)) { BlendTree sub = motion as BlendTree; motionJSON.AddField("type", "BlendTree"); motionJSON.AddField("id", TraverseBlendTree(ref sub)); } childJSON.AddField("motion", motionJSON); childJSON.AddField("timeScale", children[i].timeScale); } var blendJSON = new JSONObject(JSONObject.Type.OBJECT); json.AddField("blend", blendJSON); blendJSON.AddField("type", (int)tree.blendType); if (tree.blendType == BlendTreeType.Simple1D) { bool temp; blendJSON.AddField("parameter", controllerInfo.parameters.AddObject(tree.blendParameter, out temp).Key); var thresholdsJSON = new JSONObject(JSONObject.Type.ARRAY); blendJSON.AddField("thresholds", thresholdsJSON); for (int i = 0; i < children.Length; i++) { thresholdsJSON.Add(children[i].threshold); } blendJSON.AddField("minThreshold", tree.minThreshold); blendJSON.AddField("maxThreshold", tree.maxThreshold); } else if (tree.blendType == BlendTreeType.SimpleDirectional2D || tree.blendType == BlendTreeType.FreeformDirectional2D || tree.blendType == BlendTreeType.FreeformCartesian2D) { bool temp; blendJSON.AddField("parameterX", controllerInfo.parameters.AddObject(tree.blendParameter, out temp).Key); blendJSON.AddField("parameterY", controllerInfo.parameters.AddObject(tree.blendParameterY, out temp).Key); var positionsJSON = new JSONObject(JSONObject.Type.ARRAY); blendJSON.AddField("positions", positionsJSON); for (int i = 0; i < children.Length; i++) { var pos = children[i].position; var posJSON = new JSONObject(JSONObject.Type.ARRAY); positionsJSON.Add(posJSON); posJSON.Add(pos.x); posJSON.Add(pos.y); } } else if (tree.blendType == BlendTreeType.Direct) { var paramJSON = new JSONObject(JSONObject.Type.ARRAY); blendJSON.AddField("parameters", paramJSON); for (int i = 0; i < children.Length; i++) { if (children[i].directBlendParameter != null) { paramJSON.Add(children[i].directBlendParameter); } else { paramJSON.Add(new JSONObject(JSONObject.Type.NULL)); } } } return(treeInfo.Key); }
private void SetMotion(AnimatorState state, int layerIndex, Motion motion) { AnimatorControllerLayer[] layers = this.m_Controller.layers; state.motion = motion; this.m_Controller.layers = layers; }
private void ForDualAnalog(List <TransitionCondition> transitionConditions, Motion bothSqueezing, Motion resting, Motion leftSqueezingClip, Motion rightSqueezingClip) { AnimatorState blendState = null; foreach (var transitionCondition in transitionConditions) { var nullableTransition = GetNullableStageValue(transitionCondition); if (blendState == null) { blendState = CreateDualBlendState(bothSqueezing, resting, ToPotentialGridPosition(transitionCondition), leftSqueezingClip, rightSqueezingClip); } CreateTransition(nullableTransition, transitionCondition.Permutation, blendState, transitionCondition.TransitionDuration); } }
private static Motion CreateDualBlendTree(Motion atZero, Motion atOne, Motion atLeft, Motion atRight, string clipName, AnimatorController animatorController, bool useGestureWeightCorrection, bool useSmoothing) { ChildMotion[] motions; if (atOne == atLeft && atOne == atRight) { motions = new[] { new ChildMotion { motion = atZero, timeScale = 1, position = Vector2.zero }, new ChildMotion { motion = atOne, timeScale = 1, position = Vector2.right }, new ChildMotion { motion = atOne, timeScale = 1, position = Vector2.up }, }; } else { motions = new[] { new ChildMotion { motion = atZero, timeScale = 1, position = Vector2.zero }, new ChildMotion { motion = atLeft, timeScale = 1, position = Vector2.right }, new ChildMotion { motion = atRight, timeScale = 1, position = Vector2.up }, new ChildMotion { motion = atOne, timeScale = 1, position = Vector2.right + Vector2.up }, }; } var blendTree = new BlendTree { name = "autoBT_" + clipName, blendParameter = LeftParam(useGestureWeightCorrection, useSmoothing), blendParameterY = RightParam(useGestureWeightCorrection, useSmoothing), blendType = BlendTreeType.FreeformDirectional2D, children = motions, hideFlags = HideFlags.HideInHierarchy }; RegisterBlendTreeAsAsset(animatorController, blendTree); return(blendTree); }
private void ForDualAnalogOneHanded(List <TransitionCondition> transitionConditions, Motion squeezing, Motion resting, bool isLeftActive) { AnimatorState blendState = null; foreach (var transitionCondition in transitionConditions) { var nullableTransition = GetNullableStageValue(transitionCondition); if (blendState == null) { blendState = CreateSidedBlendState(squeezing, ToPotentialGridPosition(transitionCondition), resting, Vector3.zero, isLeftActive); } CreateTransition(nullableTransition, transitionCondition.Permutation, blendState, transitionCondition.TransitionDuration); } }
void Jump() { control = ControlStyle.CURVE; motionCurve = Motion.GetCurve(jumpDuration, lastDir, jumpSpeed); }
public static BotPosition[] Move(BotPosition bot, Motion motion, Turn turn, int turns) { List <BotPosition> moves = new List <BotPosition>(turns); if (turns > 1) { var arr = BotPosition.Move(bot, motion, turn, turns - 1); moves.AddRange(arr); bot = arr[turns - 2]; } double velocity = bot.Velocity; double heading = bot.Heading; switch (motion) { case Motion.Reverse: if (velocity >= Rules.DECELERATION) { velocity = velocity - Rules.DECELERATION; } else if (velocity > 0) { velocity = 0; } else if (velocity * -1 + Rules.ACCELERATION >= Rules.MAX_VELOCITY) { velocity = -1 * Rules.MAX_VELOCITY; } else { velocity = velocity - Rules.ACCELERATION; } break; case Motion.Accelerate: if (velocity + Rules.ACCELERATION >= Rules.MAX_VELOCITY) { velocity = Rules.MAX_VELOCITY; } else { velocity = velocity + Rules.ACCELERATION; } break; } switch (turn) { case Turn.TurnLeft: if (motion == Motion.Reverse) { heading = heading + Rules.GetTurnRate(Math.Abs(velocity)); } else { heading = heading - Rules.GetTurnRate(Math.Abs(velocity)); } break; case Turn.TurnRight: if (motion == Motion.Reverse) { heading = heading - Rules.GetTurnRate(Math.Abs(velocity)); } else { heading = heading + Rules.GetTurnRate(Math.Abs(velocity)); } break; } moves.Add(new BotPosition(bot.Location.VectorProjection(heading, velocity), heading, velocity)); return(moves.ToArray()); }
public void LogOut_Inner(bool clientSessionTerminatedAbruptly = false) { IsBusy = true; IsLoggingOut = true; if (Fellowship != null) { FellowshipQuit(false); } if (IsTrading && TradePartner != ObjectGuid.Invalid) { var tradePartner = PlayerManager.GetOnlinePlayer(TradePartner); if (tradePartner != null) { tradePartner.HandleActionCloseTradeNegotiations(); } } if (!clientSessionTerminatedAbruptly) { if (PropertyManager.GetBool("use_turbine_chat").Item) { if (GetCharacterOption(CharacterOption.ListenToGeneralChat)) { LeaveTurbineChatChannel("General"); } if (GetCharacterOption(CharacterOption.ListenToTradeChat)) { LeaveTurbineChatChannel("Trade"); } if (GetCharacterOption(CharacterOption.ListenToLFGChat)) { LeaveTurbineChatChannel("LFG"); } if (GetCharacterOption(CharacterOption.ListenToRoleplayChat)) { LeaveTurbineChatChannel("Roleplay"); } if (GetCharacterOption(CharacterOption.ListenToAllegianceChat) && Allegiance != null) { LeaveTurbineChatChannel("Allegiance"); } if (GetCharacterOption(CharacterOption.ListenToSocietyChat) && Society != FactionBits.None) { LeaveTurbineChatChannel("Society"); } } } if (CurrentActivePet != null) { CurrentActivePet.Destroy(); } if (CurrentLandblock != null) { var logout = new Motion(MotionStance.NonCombat, MotionCommand.LogOut); EnqueueBroadcastMotion(logout); EnqueueBroadcastPhysicsState(); var logoutChain = new ActionChain(); var motionTable = DatManager.PortalDat.ReadFromDat <MotionTable>((uint)MotionTableId); float logoutAnimationLength = motionTable.GetAnimationLength(MotionCommand.LogOut); logoutChain.AddDelaySeconds(logoutAnimationLength); // remove the player from landblock management -- after the animation has run logoutChain.AddAction(this, () => { if (CurrentLandblock == null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner.logoutChain: CurrentLandblock is null, unable to remove from a landblock..."); if (Location != null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner.logoutChain: Location is not null, Location = {Location.ToLOCString()}"); } } CurrentLandblock?.RemoveWorldObject(Guid, false); SetPropertiesAtLogOut(); SavePlayerToDatabase(); PlayerManager.SwitchPlayerFromOnlineToOffline(this); }); // close any open landblock containers (chests / corpses) if (LastOpenedContainerId != ObjectGuid.Invalid) { var container = CurrentLandblock.GetObject(LastOpenedContainerId) as Container; if (container != null) { container.Close(this); } } logoutChain.EnqueueChain(); } else { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: CurrentLandblock is null"); if (Location != null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Location is not null, Location = {Location.ToLOCString()}"); var validLoadedLandblock = LandblockManager.GetLandblock(Location.LandblockId, false); if (validLoadedLandblock.GetObject(Guid.Full) != null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Player is still on landblock, removing..."); validLoadedLandblock.RemoveWorldObject(Guid, false); } else { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Player is not found on the landblock Location references."); } } else { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Location is null"); } SetPropertiesAtLogOut(); SavePlayerToDatabase(); PlayerManager.SwitchPlayerFromOnlineToOffline(this); } }
void GoToGoal(Segment sCurrent, Segment sTarget) { //instead of working with endpoints, we'll just work with midpoint and rotation because the length can't change Seg pCurrent = new Seg { P = sCurrent.MidPoint.P, rotation = sCurrent.Angle }; Seg pTarget = new Seg { P = sTarget.MidPoint.P, rotation = sTarget.Angle }; Motion neededMotion = DistanceFromTarget(pTarget, pCurrent); //there are two exit cases...here we test for absolute closeness, below we test for the best action makes thing further if (Abs(neededMotion.rotation) < .05 && Abs(neededMotion.X) < .1 && Abs(neededMotion.Y) < .1) { endTarget = null; } else { ModuleUKSN UKS = (ModuleUKSN)FindModuleByType(typeof(ModuleUKSN)); Thing bestEvent = null; if (neededMotion.R > .2f) { //create a temp distination which is slightly offset ModuleBehavior mBehavior = (ModuleBehavior)FindModuleByType(typeof(ModuleBehavior)); Seg tempTarget = new Seg() { P = sTarget.MidPoint.P + new PointPlus { R = .15f, Theta = sTarget.Angle - PI / 2 }.V, rotation = 0 }; neededMotion = DistanceFromTarget(tempTarget, pCurrent); bestEvent = UKS.Labeled("E0"); if (neededMotion.Theta < -.05) { bestEvent = UKS.Labeled("E2"); } if (neededMotion.Theta > .05) { bestEvent = UKS.Labeled("E1"); } } else if (neededMotion.R > .01) { if (neededMotion.rotation < -.02) { bestEvent = UKS.Labeled("E2"); } else { bestEvent = UKS.Labeled("E1"); } } if (bestEvent != null) { Motion m = (Motion)bestEvent.Children[0].References[1].T.V; Seg nextPosition = NextPosition(pCurrent, (Motion)bestEvent.Children[0].References[1].T.V); Motion next = DistanceFromTarget(pTarget, nextPosition); //if (next.R < neededMotion.R || Abs(next.rotation) > Utils.Rad(5)) { GoToLandmark(bestEvent.References[0].T, sCurrent); doPush = 2; doBackOff = true; } //// else // { // endTarget = null; // } } //find the event with the most desireable outcome and then go the the landmark. //Thing bestEvent = null; //List<Thing> events = UKS.Labeled("Event").Children; //Seg[] distances = new Seg[events.Count]; ////first time through loop initialize array and take first action //for (int i = 0; i < events.Count; i++) //{ // distances[i] = new Seg() { P = neededMotion.P, rotation = neededMotion.rotation }; // Thing tEvent = events[i]; // Motion motion = (Motion)tEvent.Children[0].References[1].T.V; // distances[i] = NextPosition(distances[i], motion); //} ////second time through loop, add to array //for (int j = 0; j < 3; j++) //three steps //{ // for (int i = 0; i < events.Count; i++) // { // for (int k = 0; k < events.Count; k++) // { // Thing tEvent = events[k]; // Motion motion = (Motion)tEvent.Children[0].References[1].T.V; // Seg newS = NextPosition(distances[i], motion); // if (newS.Val < distances[i].Val) // { distances[i] = newS; } // } // } //} //float bestDist = float.MaxValue; //for (int i = 0; i < events.Count; i++) //last time through loop, find best //{ // if (distances[i].Val < bestDist) // { // bestDist = distances[i].Val; // bestEvent = events[i]; // } //} //Motion motion1 = (Motion)bestEvent.Children[0].References[1].T.V; //Seg newS1 = NextPosition(pCurrent, motion1); //if (newS1.Val < pTarget.Val) //{ // GoToLandmark(bestEvent.References[0].T, sCurrent); // doPush = 2; // doBackOff = true; //} //else //our best move makes things worse //{ // endTarget = null; //} } }
private AnimatorState CreateTwoDirectionsMassiveBlendState(Motion zero, Motion one, Motion minusOne, string parameterName, Vector3 gridPosition) { var clipName = UnshimName(zero.name) + " - " + UnshimName(one.name) + " - " + UnshimName(minusOne.name); var newState = _machine.AddState(SanitizeName(clipName), gridPosition); var blendTree = new BlendTree { name = "autoBT_" + clipName, blendParameter = parameterName, blendType = BlendTreeType.Simple1D, minThreshold = -1, maxThreshold = 1, useAutomaticThresholds = true, children = new[] { new ChildMotion { motion = minusOne, timeScale = 1 }, new ChildMotion { motion = zero, timeScale = 1 }, new ChildMotion { motion = one, timeScale = 1 } }, hideFlags = HideFlags.HideInHierarchy }; RegisterBlendTreeAsAsset(_animatorController, blendTree); newState.motion = blendTree; newState.writeDefaultValues = _writeDefaultsForFaceExpressions; return(newState); }
public override void Fire() { Init(); //be sure to leave this here if (GetNeuronValue("Auto") == 0) { return; } goToGoal = GetNeuronValue("Goal") == 1; ModuleBehavior mBehavior = (ModuleBehavior)FindModuleByType(typeof(ModuleBehavior)); if (mBehavior == null) { return; } Module2DModel mModel = (Module2DModel)FindModuleByType(typeof(Module2DModel)); if (mModel is null) { return; } ModuleEvent mEvent = (ModuleEvent)FindModuleByType(typeof(ModuleEvent)); if (mEvent == null) { return; } ModuleUKSN UKS = (ModuleUKSN)FindModuleByType(typeof(ModuleUKSN)); if (UKS == null) { return; } if (GetNeuronValue("ModuleBehavior", "Done") == 0) { return; } mModel.GetSegmentsFromUKS(); List <Thing> segments = mModel.GetUKSSegments(); if (segments.Count == 0) { return; } Thing t = segments[0]; //TODO: this only works with just a single item in the UKS //figure out if any motion occured Segment s = Module2DModel.SegmentFromUKSThing(t); Module2DModel.OrderSegment(s); if (GetNeuronValue("E0") == 1) { GoToLandmark(UKS.Labeled("E0").References[0].T, s); doPush = 2; doBackOff = true; return; } if (GetNeuronValue("E1") == 1) { GoToLandmark(UKS.Labeled("E1").References[0].T, s); doPush = 2; doBackOff = true; return; } if (GetNeuronValue("E2") == 1) { GoToLandmark(UKS.Labeled("E2").References[0].T, s); doPush = 2; doBackOff = true; return; } if (doPush != 0) { if (doPush == 2) { Push(s); } doPush--; return; } if (doFaceSegment) { DoFaceSegment(s); doFaceSegment = false; return; } Segment s1; if (lastPosition == null) //create objects to keep track of the target and last position { s1 = s.Clone(); lastPosition = mModel.AddSegmentToUKS(s1); lastPosition.Label = "LastPosition"; lastPosition.RemoveParent(UKS.Labeled("Segment")); lastPosition.AddParent(UKS.Labeled("SSegment")); Module2DSim mSim = (Module2DSim)FindModuleByType(typeof(Module2DSim)); if (mSim is null) { return; } Segment motionTarget = mSim.GetMotionTarget(); if (motionTarget == null) { motionTarget = new Segment(); motionTarget.P1 = new PointPlus(4, 1.5f); motionTarget.P2 = new PointPlus(4, -2.5f); motionTarget.theColor = (ColorInt)0xff; } endTarget = mModel.AddSegmentToUKS(motionTarget); endTarget.Label = "EndTarget"; //endTarget.RemoveParent(UKS.Labeled("Segment")); //endTarget.AddParent(UKS.Labeled("SSegment")); } else { s1 = Module2DModel.SegmentFromUKSThing(lastPosition); } //get motion from subtracting and then updating last position Angle rotation = s.Angle - s1.Angle; if (rotation > PI / 2) { rotation = PI - rotation; } if (rotation < -PI / 2) { rotation = PI + rotation; } Motion motion = new Motion() { P = (Point)s.MidPoint.V - s1.MidPoint.V, rotation = rotation, }; lastPosition.References[0].T.V = s.P1.Clone(); lastPosition.References[1].T.V = s.P2.Clone(); if (Abs(motion.R) > .01 || Abs(motion.rotation) > .05 && !goToGoal && !doBackOff) { //check for existing Event Thing currentEvent = MostLikelyEvent(t); if (currentEvent == null) { //add new Event Thing lm1 = mEvent.CreateLandmark(new List <Thing>() { t }); Thing t1 = mEvent.CreateEvent(lm1); Thing t3 = UKS.AddThing("m" + motionCount++, new Thing[] { UKS.Labeled("Motion") }, motion); mEvent.AddOutcomePair(t1, UKS.Labeled("Push"), t3); } return; } if (doBackOff) { DoBackOff(s); doBackOff = false; doFaceSegment = true; return; } if (goToGoal) { if (endTarget != null) { Segment s2 = Module2DModel.SegmentFromUKSThing(endTarget); GoToGoal(s, s2); return; } } Explore(s); }
private void MainUi_FormClosed(object sender, FormClosedEventArgs e) { //释放资源,关闭板卡通讯(实际应该放在程序结束前,注意如果异常终止程序而未调用释放资源操作,可能导致板卡一直被占用到情况,需要重启计算机解决) Motion.DiscardSystem(); }