2019-02-21 17:19:32 478浏览
今天扣丁学堂Unity3D培训老师给大家介绍一下关于实现鼠标控制旋转转盘的详细介绍,首先我们经常会遇到类似用鼠标旋转转盘打开开关的需求。让用户更加真实的操作设备仪器。接下来说下我的解决方案。ModelScreenPos = camera.WorldToScreenPoint(Model.transform.position);
这里有个声明,这个模型代表的是转盘,而且要保证模型的中心点在转盘中心。然后我们就要计算鼠标以模型在屏幕坐标为中心点的旋转偏移量。我们开始以鼠标按下的瞬间,偏移量为0,然后进行每帧计算偏移量。偏移量也就是旋转角度,很好计算,就是求两个向量的夹角。角度angle=Vector2.Angle(OA,OB);
q = Quaternion.FromToRotation(OA, OB);
private Vector2 ModelPos; private Vector2 mousePos; //当前鼠标位置 private Vector2 premousePos;//上一帧鼠标位置 private Quaternion q; private float RotateAngle; private Vector3 localEluer; //模型欧拉角存储变量 private bool IsSelect = false; void Start() { ModelPos = camera.WorldToScreenPoint(go.transform.position); angle = localEluer.x = info.opening; go.transform.localEulerAngles = localEluer; } public virtual void Update() { if (Input.GetMouseButtonDown(0)&&modelCamera.IsTouch()) { IsSelect = true; premousePos = mousePos=Input.mousePosition; //每次重新点击的时候都重置鼠标上一帧点击坐标 } if (Input.GetMouseButton(0)&& IsSelect) { mousePos = Input.mousePosition; RotateAngle = Vector2.Angle(premousePos - ModelPos, mousePos - ModelPos); //Debug.Log("RotateAngle+"+RotateAngle); if (RotateAngle == 0) { premousePos = mousePos; } else { q = Quaternion.FromToRotation(premousePos - ModelPos, mousePos - ModelPos); float k = q.z > 0 ? 1 : -1; localEluer.x += k * RotateAngle; //Debug.Log(localEluer.x); angle = localEluer.x = Mathf.Clamp(localEluer.x, 0, AllowAngle); //这里是项目需要 限制一下旋转圈数 go.transform.localEulerAngles = localEluer; premousePos = mousePos; } } if (Input.GetMouseButtonUp(0)) { IsSelect = false; } }
【关注微信号获取更多的学习资料】