如图所示,点击UI跟随鼠标移动并在拖动过程移动其他UI的位置`
public class Test : MonoBehaviour
{
/// <summary>
/// 记录一下当前拖拽的物体
/// </summary>
public Slot curSlot;
public List<Slot> slotList = new List<Slot>();
private Dictionary<GameObject, Slot> SlotDict = new Dictionary<GameObject, Slot>();
private void Start()
{
InitSlotList();
}
/// <summary>
/// 初始化槽子,记录数据以及添加事件
/// </summary>
private void InitSlotList()
{
foreach (Transform item in transform)
{
Slot slot = new Slot();
slot.transform = item;
slot.position = item.position;
slot.content = item.GetChild(0).gameObject;
EventTrigger trigger = slot.content.GetComponent<EventTrigger>();
AddDragEvent(trigger);
SlotDict.Add(item.gameObject, slot);
slotList.Add(slot);
}
}
private Vector2 lastPos;
private Vector2 lastMousePos;
private void OnBeginDrag(GameObject o)
{
curSlot = SlotDict[o.transform.parent.gameObject];
curSlot.content = null;
o.transform.parent = transform;
lastPos = o.GetComponent<RectTransform>().anchoredPosition;
lastMousePos = Input.mousePosition;
}
private void OnDrag(GameObject o)
{
Vector2 curMousePos = Input.mousePosition;
float x = curMousePos.x - lastMousePos.x;
float y = curMousePos.y - lastMousePos.y;
Vector2 curPos = new Vector2(lastPos.x, lastPos.y + y);
o.GetComponent<RectTransform>().anchoredPosition = curPos;
lastPos = curPos;
lastMousePos = curMousePos;
FindNearPos(o.transform.position);
}
private void OnEndDrag(GameObject o)
{
SaveContent(curSlot, o.transform);
curSlot = null;
}
private void FindNearPos(Vector2 pos)
{
foreach (var item in SlotDict.Values)
{
if (item.content!=null)
{
float dis = Mathf.Abs(pos.y - item.position.y);
if (dis<50)
{
//把最近slot的content放在curSlot中
//把当前的slot置空
Transform tmp = item.content.transform;
item.content = null;
SaveContent(curSlot, tmp);
curSlot = item;
break;
}
}
}
}
private void SaveContent(Slot slot,Transform content)
{
content.SetParent(slot.transform);
content.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
slot.content = content.gameObject;
}
private void AddDragEvent(EventTrigger e)
{
EventTrigger.Entry BeginDrag = new EventTrigger.Entry();
BeginDrag.eventID = EventTriggerType.BeginDrag;
BeginDrag.callback.AddListener((s) =>
{
OnBeginDrag(e.gameObject);
});
EventTrigger.Entry Drag = new EventTrigger.Entry();
Drag.eventID = EventTriggerType.Drag;
Drag.callback.AddListener((s) =>
{
OnDrag(e.gameObject);
});
EventTrigger.Entry EndDrag = new EventTrigger.Entry();
EndDrag.eventID = EventTriggerType.EndDrag;
EndDrag.callback.AddListener((s) =>
{
OnEndDrag(e.gameObject);
});
e.triggers.Add(BeginDrag);
e.triggers.Add(Drag);
e.triggers.Add(EndDrag);
}
}
/// <summary>
/// 槽子
/// </summary>
[System.Serializable]
public class Slot
{
/// <summary>
/// 槽子的transform
/// </summary>
public Transform transform;
/// <summary>
/// 槽子的位置
/// </summary>
public Vector2 position;
/// <summary>
/// 槽子存放的内容
/// </summary>
public GameObject content;
}