title: Drag object in Unity 2D
body: <p>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.</p>
  
  <p>I have tried to rewrite it to 2D, but I have crashed into errors, with Vectors.</p>
  
  <p>I would be very glad if you could help me rewrite it to 2D.</p>
  
  <p>Here's the code what's working in 3D:</p>
  
  <pre><code>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;
  }
  }
  </code></pre>