unity 触屏代码(三)拖拽

 private Vector3 screenPoint;
    private Vector3 offset;
    private bool isDwon = false;
    private GameObject curGameObject;

    void Start()
    {
    }

    void Update()
    {


        if (Input.touchCount == 1)
        {

            if (isDwon)
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);//从摄像机发出到点击坐标的射线
                RaycastHit hitInfo;
                if (Physics.Raycast(ray, out hitInfo))
                {
                    Debug.DrawLine(ray.origin, hitInfo.point, Color.red);//划出射线,在scene视图中能看到由摄像机发射出的射线

                    curGameObject = hitInfo.collider.gameObject;

                    Debug.Log(hitInfo.collider.gameObject.name);

                }
                else
                {
                    curGameObject = null;
                }

            }

            //开始按下
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                if (curGameObject != null)
                {
                    screenPoint = Camera.main.WorldToScreenPoint(curGameObject.transform.position);
                    offset = curGameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, screenPoint.z));

                    isDwon = false;
                }

            }
            //拖动物体
            if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                if (curGameObject != null)
                {
                    Vector3 curScreenPoint = new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, screenPoint.z);
                    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;

                    curGameObject.transform.localPosition = curPosition;

                    isDwon = false;
                }

            }

            //拖动结束
            if (Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                isDwon = true;
            }


        }


    }

猜你喜欢

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