- Home /
Question by
Rathan0104 · Apr 16, 2020 at 11:55 AM ·
grid based game
i want to draw the gameboard with square grid in unity and i am a begineer
i want to draw a gameboard that has grids in it i have centerd gameboard width as 80%of total width and height as 60% of total height i have tried but still it is not compatible for all values of row and column please look into code and help me
private void SetupGrid()
{
float height=Camera.main.orthographicSize*2f;
float width=Camera.main.aspect*height;
Debug.Log("height:"+height);
Debug.Log("width:"+width);
float possibleHeight=0.6f*height;
float possibleWidth=0.8f*width;
Debug.Log("possibleHeight:"+possibleHeight);
Debug.Log("possibleWidth:"+possibleWidth);
float eachcellWidth=possibleWidth/mWidth;
float eachcellHeight=possibleHeight/mHeight;
Debug.Log("eachcellWidth:"+eachcellWidth);
Debug.Log("eachcellHeight:"+eachcellHeight);
float cellCenterX=eachcellWidth/2;
float cellCenterY=eachcellHeight/2;
Debug.Log("cellCenterX:"+cellCenterX);
Debug.Log("cellCenterY:"+cellCenterY);
float offSetBetweenEachCell=eachcellWidth*0.15f;
float startXpos=-(mWidth/2*eachcellWidth)+cellCenterX;
float startYpos=-(mHeight/2*eachcellHeight)+cellCenterY;
Debug.Log("start X position value:"+startXpos);
Debug.Log("start Y position value:"+startYpos);
SpriteRenderer spriteRenderer=mTilePrefab.GetComponent<SpriteRenderer>();
float actualSpriteWidth=spriteRenderer.sprite.bounds.size.x;
float actualSpriteHeight=spriteRenderer.sprite.bounds.size.y;
Debug.Log("Actual Sprite width:"+actualSpriteWidth);
Debug.Log("Actual Sprite Height:"+actualSpriteHeight);
float finalCellWidth=eachcellWidth-offSetBetweenEachCell;
float finalCellHeight=eachcellHeight-offSetBetweenEachCell;
Vector3 eachCellScaleUnit=new Vector3(finalCellWidth/actualSpriteWidth,finalCellHeight/actualSpriteHeight);
Vector3 referenceVector=Vector3.one;
GameObject cell=null;
for(int i=0;i<mWidth;i++)
{
for(int j=0;j<mHeight;j++)
{
float posX=startXpos+(j*eachcellWidth);
float posY=startYpos+(i*eachcellHeight);
referenceVector.x=posX;
referenceVector.y=posY;
cell=Instantiate(mTilePrefab,referenceVector,Quaternion.identity);
cell.transform.localScale=eachCellScaleUnit;
}
}
}
but it is not square when i scale it according to row and column.
screenshot-77.png
(177.7 kB)
Comment
Your answer
Follow this Question
Related Questions
grid based game 0 Answers
Saving Grids in Grid System 1 Answer
How to find what type of tile player is on in 2D game 1 Answer
Best way to instantiate and render a grid of text 0 Answers
How to randomize the order of game objects in a grid layout? 1 Answer