继承3个处理拖拽方法的接口IBeginDragHandler, IDragHandler, IEndDragHandler文章来源:https://www.toymoban.com/news/detail-593568.html
/// <summary>
/// 实现接口的OnBeginDrag方法,处理开始拖拽时要做的事情
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
startPosition = transform.position;//获取初始位置
imageFather = transform.parent;//获取父物体的transform
transform.SetParent(canvas.transform);//将物品放在canvas最下方,确保不会被遮挡
canvasGroup.blocksRaycasts = false;//射线可以穿透物体
}
/// <summary>
/// 实现接口的OnDrag方法,处理拖动中要做的事情
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
transform.position = screenPositionToWorldPositionBy_Z(Input.mousePosition, transform.position);
}
/// <summary>
/// 通过基准点的Z点坐标,转化屏幕坐标为世界坐标
/// </summary>
/// <param name="needToFixedScreenPosition">需要转化的屏幕坐标</param>
/// <param name="baseWorldPosition">基准点(需要它的z点坐标做转换)</param>
Vector3 screenPositionToWorldPositionBy_Z(Vector3 needToFixedScreenPosition, Vector3 baseWorldPosition)
{
Vector3 baseScreenPosition = Camera.main.WorldToScreenPoint(baseWorldPosition);
needToFixedScreenPosition.z = baseScreenPosition.z;
return Camera.main.ScreenToWorldPoint(needToFixedScreenPosition);
}
文章来源地址https://www.toymoban.com/news/detail-593568.html
/// <summary>
/// 实现接口的OnEndDrag方法,处理结束时的方法
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData )
{
//获取鼠标下的物体
GameObject go = eventData.pointerCurrentRaycast.gameObject;
//交换物品
if (go.tag.Equals(Enum_Tags.InventoryItemGird)) ExchangeOfGoods(go);
//复原
else
{
transform.SetParent(imageFather);
transform.position = startPosition;
}
canvasGroup.blocksRaycasts = true;//ui事件穿透:置为不能穿透
}
/// <summary>
/// 将一个物体放在另一个物体下
/// </summary>
/// <param name="child">作为子物体</param>
/// <param name="parent">作为父物体</param>
private void SetParentAndPosition(Transform child, Transform parent)
{
child.SetParent(parent);
child.position = parent.position;
}
/// <summary>
/// 格子内的物品进行交换
/// </summary>
/// <param name="go">鼠标结束位置的格子</param>
private void ExchangeOfGoods(GameObject go)
{
Transform[] childrens = go.GetComponentsInChildren<Transform>();
bool isHaveChildren= childrens.Length > 1;
if (isHaveChildren)
{
Transform child = go.transform.GetChild(0);
SetParentAndPosition(child, imageFather);
}
SetParentAndPosition(gameObject.transform, go.transform);
}
Vector3 screenPositionToWorldPositionBy_Z(Vector3 needToFixedScreenPosition, Vector3 baseWorldPosition)
{
Vector3 baseScreenPosition = Camera.main.WorldToScreenPoint(baseWorldPosition);
needToFixedScreenPosition.z = baseScreenPosition.z;
return Camera.main.ScreenToWorldPoint(needToFixedScreenPosition);
}
到了这里,关于Unity 鼠标拖拽功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!