图片拖拽和交换位置
程序员文章站
2022-07-14 16:31:04
...
public void OnBeginDrag(PointerEventData eventData)
{
m_OriginSlotTrasnform = transform.parent; //记录当前Item的父对象位置
transform.SetParent(m_UICanvasTransform); //防止其它物体阻挡Item的渲染
m_InventoryGrid.ClearInfo();
}
public void OnDrag(PointerEventData eventData)
{
DragPos(eventData);
this.gameObject.GetComponent<Image>().raycastTarget = false; //关闭Item的射线检测
}
public void OnEndDrag(PointerEventData eventData)
{
SetTargetPosition(eventData);
}
private void SetOriginPosition(GameObject item) //回原位置
{
item.transform.SetParent(m_OriginSlotTrasnform);
item.GetComponent<RectTransform>().anchoredPosition = m_OriginSlotTrasnform.GetComponent<RectTransform>().anchoredPosition;
item.GetComponent<Image>().raycastTarget = true;
}
private void SetTargetPosition(PointerEventData eventData)
{
GameObject m_Hit = eventData.pointerCurrentRaycast.gameObject;
if (eventData.pointerCurrentRaycast.depth == 0)
{
SetOriginPosition(gameObject);
return;
}
if (m_Hit.CompareTag(TagsManager.m_InventoryGrid)) //空格子的时候
{
gameObject.transform.SetParent(m_Hit.transform);
gameObject.GetComponent<RectTransform>().anchoredPosition = m_Hit.transform.GetComponent<RectTransform>().anchoredPosition;
gameObject.GetComponent<Image>().raycastTarget = true;
}
else if (m_Hit.CompareTag(TagsManager.m_InventoryItem))
{
gameObject.transform.SetParent(m_Hit.transform.parent);
gameObject.GetComponent<RectTransform>().anchoredPosition = m_Hit.transform.parent.GetComponent<RectTransform>().anchoredPosition;
gameObject.GetComponent<Image>().raycastTarget = true;
SetOriginPosition(m_Hit);
}
else
{
SetOriginPosition(gameObject);
}
}
private void DragPos(PointerEventData eventData)
{
RectTransform RectItem = gameObject.GetComponent<RectTransform>();
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(gameObject.transform as RectTransform, eventData.position, eventData.pressEventCamera, out globalMousePos))
{
RectItem.position = globalMousePos;
}
}