Created
August 10, 2025 10:31
-
-
Save ShuraProgerMain/d54a6a3ab7c8486985ce2202b34d394a to your computer and use it in GitHub Desktop.
Search index in grid under mouse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
public class CellIndexSearcher | |
{ | |
private readonly RectTransform _cellsContainer; | |
private readonly float _cellW; | |
private readonly float _cellH; | |
private readonly float _spaceX; | |
private readonly float _spaceY; | |
private readonly int _rowCount; | |
private readonly int _columnCount; | |
public CellIndexSearcher(RectTransform cellsContainer, GridLayoutGroup grid, int rowCount, int columnCount) | |
{ | |
_cellsContainer = cellsContainer; | |
_cellW = grid.cellSize.x; | |
_cellH = grid.cellSize.y; | |
_spaceX = grid.spacing.x; | |
_spaceY = grid.spacing.y; | |
_rowCount = rowCount; | |
_columnCount = columnCount; | |
} | |
public (int row, int column) GetCellIndexUnderMouse(Vector2 mousePosition) | |
{ | |
if (RectTransformUtility.ScreenPointToLocalPointInRectangle( | |
_cellsContainer, mousePosition, null, out Vector2 localPoint)) | |
{ | |
int column = -(Mathf.FloorToInt(-localPoint.x / (_cellW + _spaceX)) - 3); | |
int row = -(Mathf.FloorToInt(localPoint.y / (_cellH + _spaceY)) - 3); | |
if (row >= 0 && row < _rowCount && | |
column >= 0 && column < _columnCount) | |
{ | |
return (row, column); | |
} | |
} | |
return (-1, -1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment