Skip to main content
1 of 4
WDUK
  • 2.1k
  • 3
  • 15
  • 24

How to do grid systems with floats given precision causes problems

Ok 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:

enter image description here

For this image the extra tiles appear when the center point is this value ( there are other numbers that cause it):

Bounds Span : 1f by 1f 
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.

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?

WDUK
  • 2.1k
  • 3
  • 15
  • 24