Vector3Int FindRaycastSquare(RaycastHit hit) { Vector3 point = hit.point; // Remember that chessboard coordiantes are permutation of Unity coordinates. ChessBoardProperties props = chessBoard.properties; // New, SRP compliant. Vector2 boardXedges = props.boardXedges; Vector2 boardYedges = props.boardYedges; Vector2 boardZedges = props.boardZedges; Vector3Int size = props.size; float squareThickness = props.squareThickness; int boardVerticalSep = props.boardVerticalSep; if (debug) { print("boardXedges = " + boardXedges); print("boardYedges = " + boardYedges); print("boardZedges = " + boardZedges); print("size = " + size); print("squareThickness = " + squareThickness); print("boardVerticalSep = " + boardVerticalSep); print("----------"); } bool withinX = boardXedges[0] < point.z && point.z < boardXedges[1]; bool withinY = boardYedges[0] < point.x && point.x < boardYedges[1]; bool withinZ = boardZedges[0] < point.y && point.y < boardZedges[1] + squareThickness; if (!(withinX && withinY && withinZ)) { print("*** nullSquare ***"); return(nullSquare); } int zCoord = 0; int xCoord = 0; int yCoord = 0; // Find level (horizontal). for (int k = 0; k < size.z; k++) { float loZ = boardZedges[0] + k * boardVerticalSep; float hiZ = boardZedges[0] + (k + 1 - squareThickness) * boardVerticalSep; withinZ = loZ < point.y && point.y < hiZ; if (withinZ) { zCoord = k; break; } } if (!withinZ) { return(nullSquare); } // Find left vertical. for (int i = 0; i < size.x; i++) { withinX = boardXedges[0] + i < point.z && point.z < boardXedges[0] + i + 1; if (withinX) { xCoord = i; break; } } // Find right vertical. for (int j = 0; j < size.y; j++) { withinY = boardYedges[0] + j < point.x && point.x < boardYedges[0] + j + 1; if (withinY) { yCoord = j; break; } } return(new Vector3Int(xCoord, yCoord, zCoord)); }