A
A
Amagitsune2021-04-01 19:34:29
Unity
Amagitsune, 2021-04-01 19:34:29

How to write manually spaced objects into a two-dimensional array?

There is a playing field with a two-dimensional array with a grid of 10x10, on which you can place houses 1x1, 2x2, 3x3, you need to create 1x1 obstacles on the field and write them into an array so that when installing houses, take into account obstacles (which can be destroyed and free up space).
I learned how to set up houses, all intersections are taken into account, but manually placed obstacles I have no idea how to add them to the array, I tried to do it through FindObjectWithTag, because the array seems to store prefabs in itself.
Please help with advice or links to useful resources for solving this problem.
Code below:

using UnityEngine;

public class BuildingGrid : MonoBehaviour
{
    public Vector2Int GridSize = new Vector2Int(10, 10);

    private Building[,] grid;
    private Building flyingBuilding;
    
    private Camera mainCamera;

    private Building ruins;

    
    
    
    private void Awake()
    {   //задаем двумерный массив
        grid = new Building[GridSize.x, GridSize.y];

        
        
        
        
        mainCamera = Camera.main;

    }
     //метод создания строения на карте, уничтожает объект, которым мы водим по сцене мышкой и ставит префаб на место клика
    public void StartPlacingBuilding(Building buildingPrefab)
    {
        if (flyingBuilding != null)
        {
            Destroy(flyingBuilding.gameObject);
        }
        
        flyingBuilding = Instantiate(buildingPrefab);
    }

    private void Update()
    {
        if (flyingBuilding != null)
        {
            var groundPlane = new Plane(Vector3.up, Vector3.zero);
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

            if (groundPlane.Raycast(ray, out float position))
            {
                Vector3 worldPosition = ray.GetPoint(position);
                //эта часть для того, чтобы объект двигался строго по целочисленным координатам
                int x = Mathf.RoundToInt(worldPosition.x);
                int y = Mathf.RoundToInt(worldPosition.z);

                //тут задаем available чтобы отображать где можно ставить и где нет, ниже проверки
                bool available = true;

                if (x < 0 || x > GridSize.x - flyingBuilding.Size.x) available = false;
                if (y < 0 || y > GridSize.y - flyingBuilding.Size.y) available = false;

                if (available && IsPlaceTaken(x, y)) available = false;

                flyingBuilding.transform.position = new Vector3(x, 0, y);
                flyingBuilding.SetTransparent(available);
                //по нажатию мыши после проверок ставим здание
                if (available && Input.GetMouseButtonDown(0))
                {
                    PlaceFlyingBuilding(x, y);
                }
            }
        }
    }
    //этот кусок для того, чтобы проверить занята клетка или нет, циклом проверяет по массиву занята ли хоть одна нужная клетка и если да возвращает false
    private bool IsPlaceTaken(int placeX, int placeY)
    {
        for (int x = 0; x < flyingBuilding.Size.x; x++)
        {
            for (int y = 0; y < flyingBuilding.Size.y; y++)
            {
                if (grid[placeX + x, placeY + y] != null) return true;
            }
        }

        return false;
    }
    //этот метод для установки здания и записи его в массив
    private void PlaceFlyingBuilding(int placeX, int placeY)
    {
        for (int x = 0; x < flyingBuilding.Size.x; x++)
        {
            for (int y = 0; y < flyingBuilding.Size.y; y++)
            {
                grid[placeX + x, placeY + y] = flyingBuilding;
            }
        }
        //красим здание в нормальный цвет после установки из скрипта на здании Building
        flyingBuilding.SetNormal();
        flyingBuilding = null;
    }



}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question