i have some problem.
my script board
private GameTile[,] board;
private Vector2 offset;
[SerializeField] float cellWidth;
[SerializeField] float cellHeight;
[SerializeField] int countX;
[SerializeField] int countY;
[SerializeField] GameObject background;
private float boardWidth;
private float boardHeight;
public void CreateBoardCells()
{
float worldHeightScreen = Camera.main.orthographicSize * 2f;
float worldWidthScreen = worldHeightScreen / Screen.height * Screen.width;
cellWidth = worldWidthScreen / (countX + 2);
cellHeight = worldHeightScreen / (countY + 6);
boardWidth = cellWidth * countX;
boardHeight = cellHeight * countY;
board = new GameTile[countX, countY];
offset = new Vector2(boardWidth * 0.5f, boardHeight * 0.5f);
for (int x = 0; x < board.GetLength(0); x++)
{
for (int y = 0; y < board.GetLength(1); y++)
{
Vector3 position = new Vector3((x * cellWidth + cellWidth / 2) - offset.x,
(y * cellHeight + cellHeight / 2) - offset.y);
board[x, y] = new board();
}
}
}
and its created a board game with sprites what i want at center relative from screen
and i try to callculate position from mouse to my grid but every time fail because i am not cool math and suppouse callculate something wrong
script callculate grid
public GameTile GetTileFromMap(Vector3 worldPos)
{
float percentegeX = (worldPos.x + boardWidth / 2) / boardWidth;
float percentegeY = (worldPos.y + boardHeight / 2) / boardHeight;
percentegeX = Mathf.Clamp01(percentegeX);
percentegeY = Mathf.Clamp01(percentegeY);
float countValueX = countX - 1;
float countValueY = countY - 1;
int x = Mathf.RoundToInt(countValueX * percentegeX);
int y = Mathf.FloorToInt(countValueY * percentegeY);
return board[x, y];
}
and it almost works as it should, just super inaccurate. for example, if you press on a cell from 0-7, then he will sometimes select it and sometimes not. apparently the surroundings are super inaccurate