Skip to content

Instantly share code, notes, and snippets.

@danhanfry
Created May 21, 2016 15:53
Show Gist options
  • Save danhanfry/5d682715c522fa160862c79661976894 to your computer and use it in GitHub Desktop.
Save danhanfry/5d682715c522fa160862c79661976894 to your computer and use it in GitHub Desktop.
Drag an Drop UI Canvas
---------------------------
using UnityEngine;
using UnityEngine.EventSystems;
public class DragB : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
this.gameObject.GetComponent<BoxCollider2D>().enabled = true;
this.gameObject.GetComponent<SpringJoint2D>().enabled = false;
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag");
bool isPositionOK = this.gameObject.GetComponent<Collider>().isCollider;
if (!isPositionOK) {
this.transform.position = eventData.position - this.gameObject.GetComponent<MousePosition>().difPosicionesVector2;
}
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
this.gameObject.GetComponent<BoxCollider2D>().enabled = false;
bool isPositionOK = this.gameObject.GetComponent<Collider>().isCollider;
if (isPositionOK) {
this.gameObject.GetComponent<SpringJoint2D>().enabled = false;
}
else{
this.gameObject.GetComponent<SpringJoint2D>().enabled = true;
}
}
}
Drag an Drop Sprite
---------------------------
using UnityEngine;
public class DragA : MonoBehaviour
{
private Vector3 diferenciaPosiciones;
void OnMouseDown()
{
diferenciaPosiciones = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
Cursor.visible = false;
}
void OnMouseDrag()
{
if (!this.gameObject.GetComponent<BoxCollider2D>())
{
Vector3 posicionRatonActual = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z);
Vector3 posicionRatonMasDiferencia = Camera.main.ScreenToWorldPoint(posicionRatonActual) + diferenciaPosiciones;
transform.position = posicionRatonMasDiferencia;
}
}
void OnMouseUp()
{
Cursor.visible = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment