private bool GetCorrectElementPosition(out CanvasRect canvasRect, out Vector3 position) { canvasRect = new CanvasRect(); position = Vector3.zero; if (!HelperSettings.GridSnap) { return(false); } canvasRect = CanvasUtil.GetCanvasRect(SelectedUIElement); var rect = canvasRect.Rect; var topLeft = new Vector3(rect.xMin, rect.yMax, 0); var gridSizeX = HelperSettings.GridSize.x; var gridSizeY = HelperSettings.GridSize.y; var canvasHalfSize = SelectedRootCanvas.pixelRect.size * 0.5f; var tx = Mathf.Clamp(Convert.ToInt32(Mathf.Round(topLeft.x / gridSizeX) * gridSizeX), -canvasHalfSize.x, canvasHalfSize.x); var ty = Mathf.Clamp(Convert.ToInt32(Mathf.Round(topLeft.y / gridSizeY) * gridSizeY), -canvasHalfSize.y, canvasHalfSize.y); position = new Vector3(tx, ty, 0); return(true); }
private void ChangeElementPositionFromGrid(RectTransform transform, CanvasRect canvasRect, Vector3 targetPos) { targetPos = SelectedRootCanvas.transform.localToWorldMatrix.MultiplyPoint(targetPos); targetPos.x -= canvasRect.PivotToSide.x; targetPos.y -= canvasRect.PivotToSide.w; SelectedUIElement.position = targetPos; }
public static CanvasRect GetCanvasRect(RectTransform trans) { var output = new CanvasRect(); if (!TryGetRootCanvas(trans.gameObject, out var canvas)) { return(output); } var position = trans.position; var pivot = trans.pivot; var sizeDelta = trans.sizeDelta; var lossyScale = trans.lossyScale; var offsetX1 = -(sizeDelta.x * pivot.x) * lossyScale.x; var offsetY1 = -(sizeDelta.y * pivot.y) * lossyScale.y; var offsetX2 = sizeDelta.x * (1f - pivot.x) * lossyScale.x; var offsetY2 = sizeDelta.y * (1f - pivot.y) * lossyScale.y; var x1 = position.x + offsetX1; var x2 = position.x + offsetX2; var y1 = position.y + offsetY1; var y2 = position.y + offsetY2; var worldToLocalMatrix = canvas.transform.worldToLocalMatrix; Vector2 min = worldToLocalMatrix.MultiplyPoint(new Vector3(x1, y1, 0)); Vector2 max = worldToLocalMatrix.MultiplyPoint(new Vector3(x2, y2, 0)); var center = worldToLocalMatrix.MultiplyPoint(position); output.Rect = Rect.MinMaxRect(min.x, min.y, max.x, max.y); output.PivotToSide = new Vector4(offsetX1, offsetY1, offsetX2, offsetY2); output.Center = center; return(output); }