unity 鼠标拖拽物体移动

    private Camera cam;//发射射线的摄像机
    private GameObject go;//射线碰撞的物体
    private Vector3 screenSpace;
    private Vector3 offset;

    private bool isdrage = false;

    void Start()
    {
        cam = Camera.main;
    }


    void Update()
    {
        if (isdrage == false)
        {
            //整体初始位置 
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            //从摄像机发出到点击坐标的射线
            RaycastHit hitInfo;

            if (Physics.Raycast(ray, out hitInfo))
            {
                //划出射线,只有在scene视图中才能看到
                Debug.DrawLine(ray.origin, hitInfo.point, Color.red);

                go = hitInfo.collider.gameObject;

                screenSpace = cam.WorldToScreenPoint(go.transform.position);
                offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));

            }


        }

        //拖拽物体不能为空
        if (go != null)
        {
            //拖拽
            if (Input.GetMouseButton(1))
            {

                Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
                Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;

                go.transform.position = currentPosition;
                isdrage = true;
            }
            else
            {
                //结束后,清空物体
                go = null;
                isdrage = false;
            }
        }


    }

猜你喜欢

转载自blog.csdn.net/weixin_42399500/article/details/84872002