[Tutorial] Making a Grid with a 2D Array

Hello guys, in this video i show you how to make a 2D array of floats and assign a random value to each index of the array, after that we take the 2D array of floats and draw a grid and assign a random color to it based off its value in the array

2 Likes

Made a follow up video showing how to place tile edges!

1 Like
1 Like

How would we change the Vertical and Horizontal to work with Pixel Perfect Camera?

public Sprite tileSprite;
    public float[,] Grid;
    int Vertical, Horizontal, Columns, Rows;
    float tileBoundsX = 0;
    float tileBoundsY = 0;

    void Start()
    {
        PixelPerfectCamera cam = Camera.main.GetComponent<PixelPerfectCamera>();

        tileBoundsX = tileSprite.bounds.extents.x;
        tileBoundsY = tileSprite.bounds.extents.y;

        Vertical = cam.refResolutionY/2 / cam.assetsPPU;
        Horizontal = cam.refResolutionX/2 / cam.assetsPPU;
        Columns = cam.refResolutionX / cam.assetsPPU;
        Rows = cam.refResolutionY / cam.assetsPPU;
        Grid = new float[Columns, Rows];

        for (int i = 0; i < Columns; i++)
        {
            for (int j = 0; j < Rows; j++)
            {
                Grid[i, j] = Random.Range(0.0f, 1.0f);
                SpawnTile(i, j, Grid[i, j]);
            }
        }
    }

    private void SpawnTile(int x, int y, float value)
    {
        GameObject g = new GameObject(x + ":" + y);
        g.transform.position = new Vector3(x -(Horizontal - tileBoundsX) , y -(Vertical - tileBoundsY));
        Debug.Log("TILE:" + g.transform.position);
        var tile = g.AddComponent<SpriteRenderer>();
        tile.sprite = tileSprite;
        tile.color = new Color(value, value, value);
    }

This leaves a tiny gap at the top and bottom of the screen…Any ideas?

The easiest way is to change your screen size/tile size to fit the math :smile:

This leaves a tiny gap at the top and bottom of the screen.


snaptube telegram web vidmate

Hello,
I want my object moving on the 2d Array tiles and at some points, displaying the index of map (x,y).
Do you have suggestion?

1 Like