I've been trying to create a grid system that can use any grid size and start at any given anchor point rather than always at 0,0.
The problem however is imprecision makes it impossible, even the simplest imprecision and i can't get it to work, yet i've seen people manage to create local grid systems... so how are they doing it?
This is how i have it setup...
I define a bounds with a minimum point and a maximum point:
public Span2D(Vector2 center, Vector2 size)
{
MinX = center.x - size.x;
MaxX = center.x + size.x;
MinY = center.y - size.y;
MaxY = center.y + size.y;
}
This has two properties that help me know the dimensions:
public float Width => Mathf.Abs(MaxX - MinX);
public float Length => Mathf.Abs(MaxY - MinY);
Now i want to draw grids of a grid size within this boundary starting at the Min
point going to the Max
point.
//grid size is some float
for (int i = 0; i < _span2D.Width / _gridSize; i++)
{
for (int j = 0; j < _span2D.Length / _gridSize; j++)
{
Grid3D grid = new Grid3D(i, 0, j, _gridSize);
// gets the mid point of the grid tile
var center = _span2D.SnapPlaneCenter(grid);
Gizmos.DrawWireCube(center, new Vector3(_gridSize, 0, _gridSize));
}
}
Now when i move the center point to some arbitrary world point, i get this problem:
For this image the extra tiles appear when the center point is this value ( there are other numbers that cause it):
Bounds Span : 2f by 2f
Grid Size : 1f by 1f
Center point : 3.97f , 2.7f (the red dot)
Notice my for loop now runs one extra time some times, i have tried casting and flooring to int, both don't fix the problem, and thats because float imprecision is the cause, for example i've had 2.000000000f cast to int as 1.. so it still didn't work if i cast the result of the division because it would be off by 1 in my for loops, see here:
When casting to int i get one less tile:
But i've seen plenty of applications use grid positions based on some local reference point, there must be some trick to get this to work properly that i am not aware of with floats... does any one know?
_span2D.Width / _gridSize
and_span2D.Length / _gridSize
operations, which are not safe to convert to an integer without considering "jump" points), I fail to see how this causes your problem, because you seem to suggest that_span2D
and_gridSize
are constant during your test, so the iteration should always run the same number of times. The problem seems to stem from variations in thecenter
point. Could you share the code for_span2D.SnapPlaneCenter(grid);
theGrid3D
class and/or theDrawWireCube
method?