给要移动的UI组件挂载
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragByInterface : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler//接口 鼠标拖拽中 开始拖拽 结束拖拽 用于UI界面
{
RectTransform rectTransform;//ui位置
CanvasGroup canvasGroup;
void Start()
{
rectTransform=GetComponent<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
}
public void OnBeginDrag(PointerEventData eventData)
{
canvasGroup.blocksRaycasts= false;//射线检测关闭
}
public void OnDrag(PointerEventData eventData)
{
//位置跟着鼠标动
rectTransform.anchoredPosition+=eventData.delta;
}
public void OnEndDrag(PointerEventData eventData)
{
canvasGroup.blocksRaycasts= true;//射线检测开始
}
public void DebugLogObject()
{
Debug.Log("拖draw");
}
}
选中的UI显示在最上方
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragWindow : MonoBehaviour, IDragHandler,IBeginDragHandler
{
RectTransform rectTransform;//ui位置
void Start()
{
rectTransform=GetComponent<RectTransform>();
}
public void OnDrag(PointerEventData eventData)
{
//位置跟着鼠标动
rectTransform.anchoredPosition+=eventData.delta;//
}
public void OnBeginDrag(PointerEventData eventData)
{
rectTransform.SetAsLastSibling();//将渲染等级移动到最后面 显示在最前面
}
}
移动世界坐标系中的物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Draw2DSprite : MonoBehaviour
{
SpriteRenderer spriteRenderer;
int startNmber;
private void Awake()
{
spriteRenderer= GetComponent<SpriteRenderer>();
startNmber= spriteRenderer.sortingOrder;
}
/// <summary>
///
/// 鼠标事件要有Collier才行
/// </summary>
private void OnMouseDrag()//unity内置鼠标拖拽 用于2d,和3d场景
{
//缺少z轴,会移动位置不对
// Vector2 cursorPor = Camera.main.ScreenToViewportPoint(Input.mousePosition);//将鼠标屏幕坐标转为世界坐标
// transform.position=new Vector2(cursorPor.x, cursorPor.y);
//获取需要移动物体的世界转屏幕坐标
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
//获取鼠标位置
Vector3 mousePos = Input.mousePosition;
//因为鼠标只有X,Y轴,所以要赋予给鼠标Z轴
mousePos.z = screenPos.z;
//把鼠标的屏幕坐标转换成世界坐标
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
//控制物体移动
transform.position = worldPos;
}
private void OnMouseEnter()//unity内置鼠标进入时
{
transform.localScale+= Vector3.one*0.07f;//放大物品缩放
spriteRenderer.sortingOrder=10;//渲染顺序排到10级 比1级 显示在屏幕前方
}
void OnMouseExit()
{
transform.localScale-= Vector3.one*0.07f;//减小物品缩放
spriteRenderer.sortingOrder=startNmber;
}
}
UI组件接受其他物体的信息
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Slot : MonoBehaviour, IDropHandler//检测拖拽事件(OnDrag)放下的操作
{
public void OnDrop(PointerEventData eventData)
{
Debug.Log("获得物体信息");
// eventData.pointerDrag. 获得拖拽物体信息
eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition=GetComponent<RectTransform>().anchoredPosition;
eventData.pointerDrag.GetComponent<DragByInterface>().DebugLogObject();
}
}