David
David

Reputation: 361

Unity : Grid Instantiating with Offset

I have a weird bug that i don't understand why it's happening, maybe someone can help.

I'm making a snake game and im doing the Grid atm. I'm instantiating the grid depending on a gameobject size, however there is an offset when the grid instantiates. it's not the same as the gameobject size i specified (the black box as shown in the image below).

enter image description here

Here's My Manager where i Instantaite the Grid

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 public class GridManager : MonoBehaviour {

[SerializeField] private GridTile gridTilePrefab; 

[SerializeField] private Transform playArea;
[SerializeField] private int gridSize = 10;

public int GridSize { 
    get { return gridSize; } 
}

private Vector3 startPoint;

public Vector3 StartPoint { 
    get { return startPoint; } 
}


private int width;
private int height;

private Transform[,] grid;

public void InitializeGrid()
{

    // Grid Size
    width = Mathf.RoundToInt (playArea.localScale.x * gridSize);
    height = Mathf.RoundToInt (playArea.transform.localScale.y * gridSize);

    grid = new Transform[width,height];

    // get the left bottom as start point
    startPoint = playArea.GetComponent<Renderer>().bounds.min;

    CreateGridTiles ();

}

private void CreateGridTiles()
{
    if (gridTilePrefab == null)
        return;


    for (int y = 0; y < height; y++) {

        for (int x = 0; x < width; x++) {

            // Get world pos of grid location
            Vector3 worldPos = GetWorldPos(x,y);
            GridTile gridTile;
            gridTile = Instantiate (gridTilePrefab, worldPos , Quaternion.identity);
            gridTile.name = string.Format ("Tile({0},{1})" , x , y );

            grid [x, y] = gridTile.transform; 

        }

    }


}


private Vector3 GetWorldPos (int x, int y)
{
    float xf = x;
    float yf = y;

    return new Vector3 (startPoint.x + (xf / gridSize) ,startPoint.y + (yf / gridSize) ,startPoint.z);

}

// Use this for initialization
void Start () {
    InitializeGrid ();
}


}

Upvotes: 0

Views: 1440

Answers (1)

David
David

Reputation: 361

The Error wasnt with the code, it was with the sprite of the tile. I changed it's pivot from center to Bottom left. Since in code my it's startPoint = playArea.GetComponent<Renderer>().bounds.min; so it will take the bottom left of the object.

Upvotes: 2

Related Questions