0

Я создаю объект при помощи функции Instantiate и назначаю ему родителем Canvas. Далее, создаю сетку при помощи Grid Layout Group размером X*Y(размер устанавливается через public переменную). Объекты в сетке имеют переменную Is_Empty. Если мы изменяем размер сетки, вызываем следующую функцию:

public void Set_Size ()
{
    float Padding = Grid.GetComponent<GridLayoutGroup>().padding.left;
    float Spacing = Grid.GetComponent<GridLayoutGroup>().spacing.x;
    float Cell_Size_X = Grid.GetComponent<GridLayoutGroup>().cellSize.x;
    float Cell_Size_Y = Grid.GetComponent<GridLayoutGroup>().cellSize.y;
    GameObject[] Cells = GameObject.FindGameObjectsWithTag("Cell");
    foreach (GameObject Cell in Cells)
    {
        if (Cell.GetComponent<Cell>().Is_Empty)
        {
            gameObject.GetComponent<RectTransform>().sizeDelta = Grid.GetComponent<GridLayoutGroup>().cellSize; // Ставим размеры как у клетки
            // Ставим позицию в сцене как у клетки
            int Pos_X = Convert.ToInt32(Cell.name.Split('_')[0]);
            int Pos_Y = Convert.ToInt32(Cell.name.Split('_')[1]);
            float Distance_X = Padding + Cell_Size_X * Pos_X  + Cell_Size_X / 2 + Pos_X * Spacing + Pos_X;
            float Distance_Y = Padding + Cell_Size_Y * Pos_Y + Cell_Size_Y / 2 + Pos_Y * Spacing + Pos_Y;
            print(Distance_X);
            print(Distance_Y);
            gameObject.GetComponent<RectTransform>().localPosition = new Vector2(Distance_X, Distance_Y);
            break; // Прерываем цикл
        }
    }
}

И все бы было хорошо, да только не тут то было. В позицию объекта Unity устанавливает значения, отличные от Distance_X и Distance_Y.
Самое главное, что если после установки значений вывести позицию объекта, то все значения будут корректными.
В случае, если изменять глобальную позицию объекта, выходит вообще какая- то бесовщина с непонятными значениями.
Помогите, пожалуйста, понять, в чем тут может быть дело.

2 ответа 2

0

Я решил проблему. Решение оказалось простым- вычитать из позиции позицию сетки. Вот код, может быть, другой человек, столкнувшийся с такой же проблемой, найдет тут решение:

public void Set_Size ()
{
    float Padding = Grid.GetComponent<GridLayoutGroup>().padding.left;
    float Spacing = Grid.GetComponent<GridLayoutGroup>().spacing.x;
    float Cell_Size_X = Grid.GetComponent<GridLayoutGroup>().cellSize.x;
    float Cell_Size_Y = Grid.GetComponent<GridLayoutGroup>().cellSize.y;
    GameObject[] Cells = GameObject.FindGameObjectsWithTag("Cell");
    foreach (GameObject Cell in Cells)
    {
        if (Cell.GetComponent<Cell>().Is_Empty)
        {
            gameObject.GetComponent<RectTransform>().sizeDelta = Grid.GetComponent<GridLayoutGroup>().cellSize; // Ставим размеры как у клетки
            // Находим позицию клетки
            int Pos_X = Convert.ToInt32(Cell.name.Split('_')[0]);
            int Pos_Y = Convert.ToInt32(Cell.name.Split('_')[1]);
            // Размер клетки * Позиция клетки + Размер клетки / 2 + Позиция клетки * Отступ клетки + Отступ клетки + Отступ сетки 
            float Distance_X = Cell_Size_X * Pos_X + Cell_Size_X / 2 + Pos_X * Spacing + Pos_X + Padding;
            float Distance_Y = Cell_Size_Y * Pos_Y + Cell_Size_Y / 2 + Pos_Y * Spacing + Pos_Y + Padding;
            // Компенсируем позицию по X и Y
            Distance_X -= Grid.GetComponent<RectTransform>().sizeDelta.x / 2;
            Distance_Y = Grid.GetComponent<RectTransform>().sizeDelta.y / 2 - Distance_Y;
            // Ставим позицию в сцене как у клетки
            gameObject.GetComponent<RectTransform>().localPosition = new Vector2(Distance_X, Distance_Y);
            break; // Прерываем цикл
        }
    }
}
0

Возможно, такой вариант будет предпочтительнее:

public Vector2 GetChildLocalPosition(RectTransform rectTransformGrid, RectTransform rectTransformChild)
{
   var localPositionGrid = (Vector2)rectTransformGrid.localPosition;
   var sizeDeltaGrid = rectTransformGrid.sizeDelta;
   var deltaGridFromCenterToLeftTop = new Vector2(-0.5f * sizeDeltaGrid.x, 0.5f * sizeDeltaGrid.y);

   var anchoredPositionChild = rectTransformChild.anchoredPosition;
   var childPosition = localPositionGrid + anchoredPositionChild + deltaGridFromCenterToLeftTop;
   return childPosition;
}

Если нужно обновить позиции в сетке принудительно:

public void UpdateGrid(LayoutGroup gridLayoutGroup)
{
   gridLayoutGroup.CalculateLayoutInputHorizontal();
   gridLayoutGroup.CalculateLayoutInputVertical();
   gridLayoutGroup.SetLayoutHorizontal();
   gridLayoutGroup.SetLayoutVertical();
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.