Unity 鼠标拖拽旋转平面内2D物体 解决方案

比如音响的音量旋钮

具体逻辑:鼠标按下时期间每帧记录鼠标位置,算出由2D物体中心到鼠标的向量角度,根据角度变化相等地调节2D物体的旋转。

缺点:无法记录拖拽转了几圈

代码:

csharp 复制代码
using UnityEngine;
using UnityEngine.EventSystems;

public class knob : MonoBehaviour, IBeginDragHandler, IDragHandler
{
    Vector2 knobPos;
    RectTransform knobRT;
    float rotAngle = 0;
    float angleRecord = 0;
    float clickRecord = 0;

    private void Start()
    {
        knobPos = RectTransformUtility.WorldToScreenPoint(null,transform.position);
        knobRT = GetComponent<RectTransform>();
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
        angleRecord = knobRT.localEulerAngles.z;
        clickRecord = Vector2Angle(Input.mousePosition);
    }

    public void OnDrag(PointerEventData eventData)
    {
        rotAngle = Vector2Angle(Input.mousePosition);
        //Debug.Log(rotAngle);
        knobRT.localEulerAngles = new Vector3(0, 0, angleRecord + rotAngle - clickRecord);
    }

    float Vector2Angle(Vector2 vector)
    {
        return Mathf.Atan2(vector.y - knobPos.y, vector.x - knobPos.x) / Mathf.PI * 180;
    }
}
相关推荐
KhalilRuan8 小时前
Unity Demo-3DFarm详解-其二
unity·游戏引擎
死也不注释13 小时前
【unity编辑器开发与拓展EditorGUILayoyt和GUILayoyt】
unity·编辑器·游戏引擎
前端开发与ui设计的老司机13 小时前
从UI设计到数字孪生实战应用:构建智慧金融的风险评估与预警平台
ui·金融
小赵小赵福星高照~14 小时前
iOS UI视图面试相关
ui·ios·面试
float_六七15 小时前
Vue:构建高效UI的渐进式框架
javascript·vue.js·ui
Zillionnn1 天前
Unreal Engine 自动设置图像
游戏引擎·虚幻
2 天前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
马特说2 天前
Unity VR手术模拟系统架构分析与数据流设计
unity·系统架构·vr
共享ui设计和前端开发人才2 天前
UI前端与数字孪生结合案例分享:智慧城市的智慧能源管理系统
前端·ui·智慧城市
甜甜不吃芥末2 天前
Windows 应用程序的 UI 框架:WPF、WinUI 3 和 UWP的差异区别
windows·ui·wpf