點擊物體並跟隨鼠標移動

	RaycastHit  hit;
    Ray         ray;            
    bool        isDrag;         //是否拖拽
    GameObject  target;         //移動目標
    Vector3     offset;         //偏移量
    void Update()
    {
        //通過鼠標點擊的位置生成射線
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Input.GetMouseButton(0))
        {
            Vector3 mousePos = Input.mousePosition;
            if (!isDrag)
            {
                //碰撞檢測
                if (Physics.Raycast(ray, out hit))
                {
                    //繪製射線,方便觀察
                    Debug.DrawLine(ray.origin, hit.point, Color.red, 5f);
                    target = hit.collider.gameObject;

                    //將射線碰撞到的物體從世界座標轉爲屏幕座標
                    Vector3 screenTarget = Camera.main.WorldToScreenPoint(target.transform.position);
                    mousePos.z = screenTarget.z;
                    //計算點擊位置和目標的偏移量
                    offset = target.transform.position - Camera.main.ScreenToWorldPoint(mousePos);
                    isDrag = true;
                }
            }
            else
            {
                Vector3 screenTarget = Camera.main.WorldToScreenPoint(target.transform.position);
                mousePos.z = screenTarget.z;
                //將mousePos從屏幕座標轉爲世界座標 + 偏移量 = 要移動的物體座標
                target.transform.position = Camera.main.ScreenToWorldPoint(mousePos) + offset;
            }
        }
        else
        {
            isDrag = false;
        }

        //UGUI中的拖拽
        //transform.GetComponent<RectTransform>().position = Input.mousePosition;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章