Hello
If we want to use a certain number of rectangles
For example, 200 pieces of 10x20
Due to the variable ratio in some phones, the rectangles could no longer be square and became rectangular.
If we want them to be almost square, we usually do it this way
Now, how can we design a script that has, for example, 25 texture entries and divides the page into equal squares exactly like this and randomly assigns each of the textures to these cells to create an effect like this?
Of course, if the number of rectangles was constant, we could do this in the patch editor, but due to the variable number of rectangles, I think we have to use a script.
The shuffling could be done in script. Here’s the function that I use:
Here’s a simple packing script. It’s vanilla js so you can run it in your browser console.
function packSquaresInRectangle(rectangleWidth, rectangleHeight, numSquares) {
// Calculate the square size based on the rectangle's dimensions and the number of squares.
let totalArea = rectangleWidth * rectangleHeight;
let squareSize = Math.sqrt(totalArea / numSquares);
// The packing function takes the width and height of the rectangle and returns the packed squares.
function pack(width, height) {
let squares = [];
let currentX = 0;
let currentY = 0;
for (let i = 0; i < numSquares; i++) {
squares.push({ x: currentX, y: currentY });
currentX += squareSize;
if (currentX + squareSize > width) {
currentX = 0;
currentY += squareSize;
}
}
return squares;
}
let packedSquares = pack(rectangleWidth, rectangleHeight);
return {
rectangle: { width: rectangleWidth, height: rectangleHeight },
squares: packedSquares,
};
}
// Example usage:
let rectangleWidth = 50;
let rectangleHeight = 50;
let numSquares = 25;
let result = packSquaresInRectangle(rectangleWidth, rectangleHeight, numSquares);
console.log("Rectangle:", result.rectangle);
console.log("Squares:", result.squares);
You’ll need to send the square size back to the patches to generate the shader. There will also need to be some extra calculation to determine the unfilled area on the edges, which you will use to scale up your texture to fill the space.