I’m creating a small RTS project and trying to implement some kind of unit formation
I’m trying to create a grid of cells which will be the formation for all the selected units. I want the formation to be as close to a square as possible.
The problem is the selected unit count might not necessarily have a count which has a square root.
This is fine when the count has a square root such as 100 units. I could just do the following
My problem lies when the number is something random like 74.
I know that I could grab all the factors and get the 2 closest factors and loop through them. But this won’t work properly
Can anyone think of a way that I could create a grid formation when the cell counts would be random?
You probably don’t want to do that (because the result for primes would just be a line), but I’m not sure what you mean by “won’t work properly”.
Your problem is a bit unclear: “As close to a square as possible” could mean a few different things, in mathematical terms.
I would think what you probably want to do is to round up to the next square and then just put units into that grid until you run out, leaving some empty spaces. (Maybe with some additional rules about where you position the empty spaces to make it look neat, like centering the last row, or removing equally from all corners or something.)
@Kurt-Dekker@Antistone So in the case of prime units this is what I had in mind with regards to it thinking it won’t work. If was to say have 13 units selected. I’d want to create a grid like so
Obviously, 13 being a prime number, I’d only get factors 1 and 13 which would be no good to create a grid from. I would need a 4 x 4 grid in order to create this pattern.
My problem is how I get there. Despite say, 74 not being a prime number. I still don’t really know how I could programmatically figure out the grid I would need. I know myself it’s a 9 x 9 grid, but I don’t know how to get there via the code.
I haven’t even got to the stage to how I would plot the units positions using the grid itself but will hopefully figure that out once I’ve got a starting point.