How to drag and drop item in Unity3D

 




For dragging and dropping to work we will need to first grab the Game Object and ensure while the Game Object remains grabbed it's position reciprocates the mouse position. This will work fine for not only PC bug mobile devices as well.


First define GameObject which we will be dragging.


public GameObject selectedPiece;



Now inside Update method we will give reference to touched/clicked object and while there is a reference available to an game object(selectedPiece;) we will move that object to mouse position.

When the reference is remove, object won't move therefore dropped.


void Update(){


RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

if (Input.GetMouseButtonDown(0)){


if(hit.transform != null)

            {

                if (hit.transform.CompareTag("PIECE"))

                {

                    selectedPiece = hit.transform.gameObject;

                }

            }

}


if (Input.GetMouseButtonUp(0))

        {

            selectedPiece = null;

        }


        if (selectedPiece != null)

        {

            Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);


            selectedPiece.transform.position = new Vector3(mousePosition.x, mousePosition.y, 0);


        }


}








Comments