To use touch & raycasting to *drag and drop* a game object...

I am trying to make a simple way to use mobile touch to actually move (i.e., drag and then drop) a game object from one place to another.

To at least detect the touch on the desired object, I was very happy to use the great answer @rob5300 gave to: Best way to detect touch on a GameObject - Questions & Answers - Unity Discussions

It successfully detects the touch on the object, but now I can’t quite find the most graceful way to make it so that if the person keeps their finger on the touched object and starts moving the touch around, the object follows their finger, until the person stops the touch.

I will paste my code below.

Key point: The below code sits out in its own GameObject… not inside the draggable object… because later I want it to work with multiple objects the person might try to drag.

You can see where my final debug.log says “At this point I sure wish the object would get dragged around…” Can you tell me how, at that point, I can make the gameobject follow the touch finger’s moves until the person stops the touch? THANKS! --Eric

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RaycastTest : MonoBehaviour
{

    Vector3 touchPosWorld;
    bool carrying;

    //Change me to change the touch phase used.
    TouchPhase touchPhase = TouchPhase.Began;

    // Update is called once per frame
    void Update()
    {
        //We check if we have more than one touch happening.
        //We also check if the first touches phase is Ended (that the finger was lifted)
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == touchPhase)
        {
            //We transform the touch position into word space from screen space and store it.
            touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

            Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);

            //We now raycast with this information. If we have hit something we can process it.
            RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);

            if (hitInformation.collider != null)
            {
                //We should have hit something with a 2D Physics collider!
                GameObject touchedObject = hitInformation.transform.gameObject;
                //touchedObject should be the object someone touched.
                Debug.Log("Touched " + touchedObject.transform.name);
                if (touchedObject.transform.name == "p-circle-p")
                {
                    Debug.Log("Touched the draggable one! I sure wish it would start dragging the item until I let go.");
                }

            }
        }
    }
}

Not exactly answering your question, as you asked, but if you just want to be able to drag things around, here is a script I found a while back, can’t remember where I got it, or I would give them proper credit.

using UnityEngine;
using UnityEngine.EventSystems;

public class Dragger : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    Camera mainCamera;
    float zAxis = 0;
    Vector3 clickOffset = Vector3.zero;
    // Use this for initialization
    void Start()
    {
        mainCamera = Camera.main;
        if (mainCamera.GetComponent<Physics2DRaycaster>() == null)
            mainCamera.gameObject.AddComponent<Physics2DRaycaster>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
	zAxis=transform.position.z;
        clickOffset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, zAxis)) + new Vector3(0, 3, 0);
        transform.position = new Vector3(transform.position.x, transform.position.y, zAxis);
    }

    public void OnDrag(PointerEventData eventData)
    {
        //Use Offset To Prevent Sprite from Jumping to where the finger is
        Vector3 tempVec = mainCamera.ScreenToWorldPoint(eventData.position) + clickOffset;
        tempVec.z = zAxis; //Make sure that the z zxis never change
        

        transform.position = tempVec;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        transform.position = new Vector3(transform.position.x, transform.position.y, -1);
    }

    //Add Event System to the Camera
    void addEventSystem()
    {
        GameObject eventSystem = new GameObject("EventSystem");
        eventSystem.AddComponent<EventSystem>();
        eventSystem.AddComponent<StandaloneInputModule>();
    }
}

Attach this script to an object, and you should be able to use touch to drag that object around.

I had modified this script for my game. I just tried to undo the modifications I made. Hopefully I didn’t introduce any issues when I did this, but if I did, let me know and I’ll figure it out :slight_smile:

Hope this helps,
-Larry