Table of contents
2. Sprite Renderer drag and drop
1.UI --- Image drag and drop
The control script needs to inherit the three interfaces of IBeginDragHandler, IEndDragHandler, and IDragHandler and implement the interface methods
⚠️ Note: Add Colider 2D collision body
public class ItemContr : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
private RectTransform rectTrans;
private void Awake()
{
rectTrans = GetComponent<RectTransform>();
}
private void OnTriggerEnter2D(Collider2D other)
{
//....
}
private void OnTriggerExit2D(Collider2D other)
{
//....
}
public void OnBeginDrag(PointerEventData eventData)
{
rectTrans.SetAsLastSibling();
}
public void OnDrag(PointerEventData eventData)
{
rectTrans.anchoredPosition += eventData.delta;
}
public void OnEndDrag(PointerEventData eventData)
{
rectTrans.SetSiblingIndex(1);
}
}
2. Sprite Renderer drag and drop
⚠️Note:
1. Add Collider2D collision body
2. The Projection of Camera needs to be set to Orthographic mode
using UnityEngine;
public class ItemContr : MonoBehaviour
{
private Camera _camera;
private void Awake()
{
_camera = GameObject.FindGameObjectWithTag("camera").GetComponent<Camera>();
}
void Start()
{
}
void Update()
{
}
private void OnMouseDown()
{
//Debug.LogError("down");
}
private void OnMouseDrag()
{
if (_camera == null)
{
return;
}
//leftMax -2.7 rightMax 2.9 topMax 1.77 downMax -1.25
var offsetX = _camera.ScreenToWorldPoint(Input.mousePosition).x;
var offsetY = _camera.ScreenToWorldPoint(Input.mousePosition).y;
transform.position = new Vector3(Mathf.Clamp(offsetX, -2.7f, 2.9f), Mathf.Clamp(offsetY, -1.25f, 1.77f), 0);
}
private void OnMouseUp()
{
//Debug.LogError("Up");
}
private void OnTriggerEnter2D(Collider2D collision)
{
//Debug.LogError("11111");
}
private void OnTriggerExit2D(Collider2D collision)
{
//Debug.LogError("2222");
}
}