unity实现方向盘转动效果

【unity实现方向盘转动效果】本文实例为大家分享了unity实现方向盘转动效果的具体代码,供大家参考,具体内容如下
效果 手指或鼠标拖动方向盘旋转,有角度限制,松手后自动回转。
unity实现方向盘转动效果
文章图片

代码 将代码添加到方向盘Image上。
注意需要赋值Canvas。

using UnityEngine; using UnityEngine.EventSystems; public class SteeringWheel : MonoBehaviour,IDragHandler,IEndDragHandler{public Canvas CanvasRoot; //需要指定画布 private RectTransform m_RectTransform; //坐标private bool m_IsFirst = true; //用于记录第一帧按下鼠标时鼠标的位置,便于计算private Vector3 m_CurrentPos; //记录当前帧鼠标所在位置private bool m_IsClockwise; //是否顺时针private float m_RoundValue = https://www.it610.com/article/0; //记录总的旋转角度 用这个数值来控制一圈半private bool m_IsTuringSteeringWheel; //是否在转方向盘 用这个判断复位public void OnDrag(PointerEventData eventData){m_IsTuringSteeringWheel = true; Vector2 pos; if (RectTransformUtility.ScreenPointToLocalPointInRectangle(m_RectTransform, Input.mousePosition, CanvasRoot.worldCamera, out pos))//获取鼠标点击位置{pos.x = pos.x + (Screen.width / 2) - GetComponent().position.x; pos.y = pos.y + (Screen.height / 2) - GetComponent().position.y; Vector3 pos3 = new Vector3(pos.x, pos.y, 0); //计算后鼠标以方向盘圆心为坐标原点的坐标位置if (m_IsFirst){m_CurrentPos = pos3; m_IsFirst = false; }Vector3 currentPos = Vector3.Cross(pos3, m_CurrentPos); //计算当前帧和上一帧手指位置 用于判断旋转方向if (currentPos.z > 0){m_IsClockwise = true; }else if (currentPos.z < 0){m_IsClockwise = false; }if (m_CurrentPos != pos3)//范围内让方向盘随着手指转动{if (m_IsClockwise){if (m_RoundValue <= 180){m_RoundValue += Vector3.Angle(m_CurrentPos, pos3); transform.Rotate(new Vector3(0, 0, -Vector3.Angle(m_CurrentPos, pos3))); }}else{if (m_RoundValue >= -180){m_RoundValue -= Vector3.Angle(m_CurrentPos, pos3); transform.Rotate(new Vector3(0, 0, Vector3.Angle(m_CurrentPos, pos3))); }}}m_CurrentPos = pos3; }}public void OnEndDrag(PointerEventData eventData){m_IsFirst = true; m_IsTuringSteeringWheel = false; }void Start(){CanvasRoot = GameObject.Find("Canvas").GetComponent(); m_RectTransform = CanvasRoot.transform as RectTransform; }void Update(){if (!m_IsTuringSteeringWheel && m_RoundValue != 0)//复位{if (m_RoundValue >= 0){m_RoundValue -= 8f; //复位速度if (m_RoundValue < 0)m_RoundValue = https://www.it610.com/article/0; transform.rotation = Quaternion.Euler(new Vector3(0, 0, -m_RoundValue)); }else{m_RoundValue += 8f; if (m_RoundValue> 0)m_RoundValue = https://www.it610.com/article/0; transform.rotation = Quaternion.Euler(new Vector3(0, 0, -m_RoundValue)); }}}}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读