I create random sized 2d grids and set the camera to middle of the grid, I also try to understand orthographic size and adjust it to fit whole grid but I guess I fail, Here are the code snippet and the fitting problem:
I would also be appreciated if you have any other advice for my programming and design style.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.WSA;
public class Grid2D : MonoBehaviour
{
[SerializeField] private int _width, _height;
[SerializeField] private Tile _tilePrefap;
[SerializeField] private Camera _cam;
void Start()
{
GenerarteGrid();
SetCamera(_width,_height);
}
// Update is called once per frame
void Update()
{
}
private void GenerarteGrid()
{
for (int i = 0; i < _width; i++)
{
for (int j = 0; j < _height; j++)
{
var tile = Instantiate(_tilePrefap, new Vector3(i, j, 0), Quaternion.identity);
tile.transform.parent = transform;
tile.name = j + " " + i;
}
}
}
private void SetCamera(int x, int y)
{
_cam.orthographicSize = (float) _height / 2 + 0.5f ;
_cam.transform.position = new Vector3((float)x / 2 - 0.5f, (float)y / 2 - 0.5f, 0);
}
}
You have to check whether to match the height or width like e.g.
_cam.orthographicSize = width > height ? width / camera.aspect / 2f : height / 2f;
// optional space
_cam.orthographicSize += 0.5f;