Skip to content

Instantly share code, notes, and snippets.

@nooralibutt
Created November 17, 2015 10:55
Show Gist options
  • Save nooralibutt/a7b84df4dee70c84bc26 to your computer and use it in GitHub Desktop.
Save nooralibutt/a7b84df4dee70c84bc26 to your computer and use it in GitHub Desktop.
Free Drag Drop Item Script for uGUI Unity C#
// Canvase should be Screen Space - Camera
// Attach a Event Trigger Script to image you want to Drag Drop
// Add Begin Drag and Drap Event Listener
// Attach this script to that image
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
public class DragDropItem : MonoBehaviour
{
// To keep track of drag position
private Vector2 prevDragPos;
public void OnDragBegin(BaseEventData data) {
// 0- Save Begin drag position to use it OnDrag
prevDragPos = getScreenPosition ();
}
public void OnDrag (BaseEventData data)
{
// 1- Get current position on screen
Vector3 point = getScreenPosition ();
// 2- Calc difference of movement with prev Drag pos
float x = point.x - prevDragPos.x;
float y = point.y - prevDragPos.y;
// 3- Assign difference to current object's Transform
Vector3 resPos = transform.position;
resPos.x += x;
resPos.y += y;
transform.position = resPos;
// 4- Now current Drag position become prev one
prevDragPos = point;
}
private static Vector3 getScreenPosition ()
{
// Get current position on screen
Vector3 curPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
curPos.z = 0;
return curPos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment