You are going to want to do a simple raycast to pickup the object and use a TargetJoint2D component to have the object anchor based on your mouse position relative to the object and track your mouse position. This is a basic working version. I would look into more raycasting stuff as it is extremely useful to know how to do. Hope this helps!
Attach this script to your box with the rigidbody2D and its box collider.
Attach this script to your camera, or just whatever object since it doesn’t rely on the object it is attached to but make sure there is only one of them in the scene at a time.
public class BoxDrag : MonoBehaviour
{
private Dragable _drag_target;
void Start()
{
_drag_target = null;
}
void Update ()
{
if (_drag_target == null) {
if (Input.GetMouseButtonDown (0)) {
Vector2 mouse_pos = (Vector2)Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (mouse_pos, Vector2.zero);
if (hit.collider != null) {
Dragable dragable = hit.collider.GetComponent<Dragable> ();
if (dragable != null) {
_drag_target = dragable;
_drag_target.BeginDrag (mouse_pos);
}
}
}
}
if (_drag_target != null) {
Vector2 mouse_pos = (Vector2)Camera.main.ScreenToWorldPoint (Input.mousePosition);
_drag_target.UpdateDrag (mouse_pos);
if (Input.GetMouseButtonUp (0)) {
_drag_target.EndDrag ();
_drag_target = null;
}
}
}
}
When pressing down the mouse shoot a raycast and see if the mouse is over the cube, if so have the cube follow the mouse until you release the mouse. you can mainly do this with simply if statements like:
if(Input.GetButton(“Fire1”)) {