UI布局相关
- 需求-卡牌游戏
- 跟着鼠标拖动
- 判定ui是否在其他ui区域内
需求-卡牌游戏
跟着鼠标拖动
实现IDragHandler接口
public void OnDrag(PointerEventData eventData)
{Vector3 globalMousePos;if (RectTransformUtility.ScreenPointToWorldPointInRectangle(_mainCanvas, eventData.position, eventData.pressEventCamera, out globalMousePos)){this.transform.position = globalMousePos;this.transform.rotation = _mainCanvas.rotation;}
}
判定ui是否在其他ui区域内
实现IEndDragHandler接口
// 假设你已经有了四个区域边界的RectTransform引用 public RectTransform[] regions;public void OnEndDrag(PointerEventData eventData)
{// 转换当前UI元素的RectTransform到Canvas的坐标系中 Vector2 localPoint;for (int i = 0; i < regions.Length; i++){//将选中的点转换为Image区域内的本地点RectTransformUtility.ScreenPointToLocalPointInRectangle(regions[i], eventData.position, null, out localPoint);Vector2 pivot = regions[i].pivot;Vector2 normalizedLocal =new Vector2(pivot.x + localPoint.x / regions[i].sizeDelta.x, pivot.y + localPoint.y / regions[i].sizeDelta.y);if ((normalizedLocal.x >= 0 && normalizedLocal.x <= 1) && ((normalizedLocal.y >= 0 && normalizedLocal.y <= 1))){Debug.Log($"拖拽到区域{i+1}");// 假设rectTransform是包含需要刷新布局的UI元素的RectTransformif (i == 3){LayoutRebuilder.ForceRebuildLayoutImmediate(regions[3]);}return;}}LayoutRebuilder.ForceRebuildLayoutImmediate(regions[3]);}