Drag object in Unity 2D

Zwiebel picture Zwiebel · Apr 18, 2014 · Viewed 33.1k times · Source

I have looked for an object dragging script for Unity 2D. I have found a good method on the internet, but it seems it's just working in Unity 3D. It's not good for me as I'm making a 2D game and it's not colliding with the "walls" in that way.

I have tried to rewrite it to 2D, but I have crashed into errors, with Vectors.

I would be very glad if you could help me rewrite it to 2D.

Here's the code what's working in 3D:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]

public class Drag : MonoBehaviour {
    private Vector3 screenPoint;
    private Vector3 offset;

void OnMouseDown() {

    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

void OnMouseDrag()
{
    Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    transform.position = curPosition;
}
}

Answer

Alex Jolig picture Alex Jolig · Jul 16, 2016

For the ones who have problem using this code, I used ScreenPointToRay to use algebraic raycasts (fast) to determine how far the object should be placed from the camera. This works in both orthographic and perspective cameras

Also, the object could use Collider to able to be dragged around. So there's no point using [RequireComponent(typeof(BoxCollider2D))].

The final code which worked fine for me is:

using UnityEngine;
using System.Collections;

public class DragDrop : MonoBehaviour {
    // The plane the object is currently being dragged on
    private Plane dragPlane;

    // The difference between where the mouse is on the drag plane and 
    // where the origin of the object is on the drag plane
    private Vector3 offset;

    private Camera myMainCamera; 

    void Start()
    {
        myMainCamera = Camera.main; // Camera.main is expensive ; cache it here
    }

    void OnMouseDown()
    {
        dragPlane = new Plane(myMainCamera.transform.forward, transform.position); 
        Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition); 

        float planeDist;
        dragPlane.Raycast(camRay, out planeDist); 
        offset = transform.position - camRay.GetPoint(planeDist);
    }

    void OnMouseDrag()
    {   
        Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition); 

        float planeDist;
        dragPlane.Raycast(camRay, out planeDist);
        transform.position = camRay.GetPoint(planeDist) + offset;
    }
}