编辑器开发-代码实现Unity拖拽移动操作轴

2023-12-14 20:35:53

视频效果:

工程网盘链接:

链接:https://pan.baidu.com/s/1l_9mcvdPuCgNqFp4mPVKuQ?
提取码:1212

关键代码:

    /// <summary>
    /// 鼠标按下
    /// </summary>
    private Vector3 offset;
    private void OnMouseDown()
    {
        isDrag = true;
        //鼠标按下表现
        SetSelectView();
        //根据模型坐标系确定移动方向
        moveDir = transform.up;
        startPos = operaObj.transform.position;
        startCamDis = Vector3.Distance(Camera.main.transform.position, startPos);
        //记录第一次点击时与物体的坐标点的偏移值
        offset=startPos-GetPointToPro(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,startCamDis)));
    }
    
    private Vector3 axisPos;
    private Vector3 worldPos;
    private void OnMouseDrag()
    {
        axisPos = Input.mousePosition;
        axisPos.z = startCamDis;
        worldPos = Camera.main.ScreenToWorldPoint(axisPos);
        worldPos = GetPointToPro(worldPos) + offset;
        operaObj.transform.position = worldPos;
    }

    /// <summary>
    /// 鼠标抬起
    /// </summary>
    private void OnMouseUp()
    {
        isDrag = false;
        //鼠标抬起表现
        SetNoSelectView();
    }
    
    private Vector3 a;
    private Vector3 b;
    /// <summary>
    /// 求坐标点在移动方向的投影坐标
    /// </summary>
    /// <param name="targetPos"></param>
    /// <returns></returns>
    private Vector3 GetPointToPro(Vector3 targetPos)
    {
        a = targetPos - startPos;
        b = moveDir;
        return startPos + Vector3.Dot(a,b)*moveDir;
    }

文章来源:https://blog.csdn.net/ysn11111/article/details/135002601
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。