using Microsoft.MixedReality.Toolkit.UI.BoundsControl; using UnityEngine; /// /// 旋转螺母 /// public class TurnTheScrew : Device { private Vector2 MyPos; /// /// 当前位置 /// private Vector2 currentPos; public Transform currentTran; /// /// 上一帧位置 /// private Vector2 lsatPos; private Quaternion q; /// /// 旋转角度 /// private float RotateAngle; public OneValueSyncObject localEluer; /// /// 是否旋转 /// private bool IsSelet = false; /// /// 旋转同步 /// public FunctionSync_PositionRoate sync_MyRoate; /// /// 旋转方向 /// public OneValueSyncObject sync_dir; private float minAngle = -720; private float maxAngle = 180; private float minPosX = 3.815f; private int currentState = -1; // Start is called before the first frame update public override void Start() { //sync_MyRoate.GetControl(); MyPos = new Vector2(transform.forward.y, transform.forward.z); } // Update is called once per frame void Update() { if (IsSelet) { currentPos = new Vector2(currentTran.forward.y, currentTran.forward.z); //向量夹角 RotateAngle = Vector2.Angle(lsatPos - MyPos, currentPos - MyPos); if (RotateAngle == 0) { lsatPos = currentPos; } else { q = Quaternion.FromToRotation(lsatPos - MyPos, currentPos - MyPos); float k = q.z < 0 ? 1 : -1;//k为正则顺时针 为负则为逆时针 localEluer.myvector3.z += k * RotateAngle; localEluer.myvector3.z = Mathf.Clamp(localEluer.myvector3.z, minAngle, maxAngle); localEluer.SendSync(); transform.localEulerAngles = localEluer.myvector3; if (localEluer.myvector3.z == minAngle) { LimitMinAngle(-1); } else if (localEluer.myvector3.z >= maxAngle && maxAngle != -360) { LimitMaxAngle(1); } else { currentState = 0; } lsatPos = currentPos; } } transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, 3.815f - localEluer.myvector3.z * 0.01f / 360); transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, Mathf.Clamp(transform.localPosition.z, minPosX, 3.835f)); if (!string.IsNullOrEmpty(GetComponentInChildren().ConnectObj.mystring) && sync_dir.myint != 1) { GetComponent().Active = true; maxAngle = -360; minPosX = 3.825f; if (localEluer.myvector3.z == maxAngle) { sync_dir.myint = 1; sync_dir.SendSync(); if (sync_dir.action_apprisedetail != null) sync_dir.action_apprisedetail.Invoke(); GetComponent().Active = false; } } } public void LimitMaxAngle(int state) { if (currentState != state) { currentState = 1; GetComponent().Active = false; Invoke("Resetvoke", 2); } } public void LimitMinAngle(int state) { if (currentState != state) { currentState = -1; sync_dir.myint = -1; sync_dir.SendSync(); if (sync_dir.action_apprisedetail != null) sync_dir.action_apprisedetail.Invoke(); GetComponent().Active = false; } } public void Resetvoke() { if (localEluer.myvector3.z != -360) { transform.GetComponent().Active = true; } } public void RotateStarted() { IsSelet = true; lsatPos = currentPos = currentTran.forward; sync_MyRoate.GetControl(); } public void RotateStoped() { IsSelet = false; sync_MyRoate.ReleaseControl(); } }