How do you drop and drop a 2D object in unity 5?

I’m trying to make it so I can click on objects falling from the top of the screen, and drop them to a certain point, then letting go so it continues falling.

However I’m really new to unity and can’t find and recent answers, I was wondering if someone could lend a helping hand ^^ I’m not gonna ask for exact code cuz then I might not learn anything, but if someone knows the functions I might need and maybe an idea of just how it should be implemented I’d appreciate the help :slight_smile:

Put a collider on each object you want to make clickable. Set a bool for drag in OnMouseDown(), move it if dragging in Update() and toggle the flag back in OnMouseUp(). That’s the gist of it anyway :slight_smile:

Another way of doing it is to move clicking and handling into a generic manager script instead of on each project. This can be useful for multiple pickups.

1 Like

I’ll give this a go, thanks :slight_smile:

Ok so its kind of working, but when I drag the object, in looks like im making a new one instead of moving it, almost like im making a trail of this object behind my mouse

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

public class DragandDrop : MonoBehaviour
{

    private bool isDragging;
    private Vector3 targetPos;
  
    // Use this for initialization
    void Start ()
    {
        isDragging = false;
    }
  
    // Update is called once per frame
    void Update ()
    {
        if(isDragging == true)
        {
            targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            targetPos.z = transform.position.z;
            Instantiate(this, targetPos, Quaternion.identity);
        }
    }

    void OnMouseDown()
    {
        isDragging = true;
    }

    void OnMouseUp()
    {
        isDragging = false;
    }
}

not quite sure whats up.

Taking a second look, it’s probably because I used instantiate, thats basically creating right? Not sure what to use instead though

Yeah, you’re instantiating a new one every Update(), which is not a great idea in the long run. Or even for two frames :wink:

Just set the transform.position to the mouse position. You could also set the Z position to somewhere nearer the camera.

1 Like

Tried XD

if(isDragging == true)
        {
            targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            targetPos.x = transform.position.x;
            targetPos.y = transform.position.y;
            this.transform.position = new Vector2(targetPos.x, targetPos.y);
        }

You’re setting the x/y positions of the object to the x/y positions of the object. Remove lines 4 and 5.

1 Like

:o progress! :smile:

1 Like

Later on this is going to do weird things with clicks on the UI. My preference is to use the event system interfaces. It’s slightly more boilerplate code, but it’s worth playing nice with the UI.

You will need to add a Physics2DRaycaster to the camera.