Freezing Y axis for drag and drop script

Hello everyone, can anyone explain how to freeze the move for Y axis in this script?

private GameObject target;
    private bool isMouseDragging;
    private Vector3 screenPosition;
    private Vector3 offset;

    GameObject ReturnClickedObject(out RaycastHit hit)
    {
        GameObject targetObject = null;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray.origin, ray.direction * 10, out hit) && (hit.collider.tag == "Draggable"))
        {
            targetObject = hit.collider.gameObject;
        }
        return targetObject;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hitInfo;
            target = ReturnClickedObject(out hitInfo);
            if (target != null)
            {
                target.transform.position = new Vector3(target.transform.position.x, -6f, target.transform.position.z);
                isMouseDragging = true;
                Debug.Log("our target position :" + target.transform.position);
                //Here we Convert world position to screen position.
                screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
                offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            isMouseDragging = false;
            target.transform.position = new Vector3(2.5f, -6f, 40f);
        }

        if (isMouseDragging)
        {
            //tracking mouse position.
            Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);


            //convert screen position to world position with offset changes.
            Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
            Debug.Log("camera" + Camera.main.ScreenToWorldPoint(currentScreenSpace));
            Debug.Log("offset" + offset);

            //It will update target gameobject's current postion.
            target.transform.position = currentPosition;
        }

    }

Before line 52 you can set the currentPosition.y field equal to whatever you like.

If you need to choose what to set it to, perhaps you should copy the y position to a member variable at the moment you want to freeze it, such as when the mouse goes down.

1 Like

Thanks sir

1 Like