目录
1.UI ---Image拖拽
控制脚本需继承IBeginDragHandler, IEndDragHandler, IDragHandler 三个接口 并实现接口方法
⚠️注意:添加Coliider 2D碰撞体
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拖拽
⚠️注意:
1.添加Collider2D 碰撞体
2.Camera的Projection 需设置为Orthographic模式
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");
}
}