What I'm trying to achieve is rendering a (huge) tile grid over a terrain. For that I'm using a generated mesh of quads, one for every tile, whose vertices Y value is the same of the terrain to "shape" this mesh like the terrain.

My problem is that this mesh should be rendered always over the terrain, keeping every other object rendered on top of this grid. As you should guess I'm a beginner in shader programming. So here are some caps:

Rendering the mesh with simple unlit transparent shader (with ZTest, ZWrite and Cull values):

enter image description here enter image description here As you can see there are problems with the z-fighting, when the grid should always be drawn on top. Rising the terrain won't solve it, since the terrain have lots of "peaks" and the quads should be planes with lots of vertex to be able to follow the terrain (or rising a lot the grid which will cause it to float over the terrain).

Changing the ZTest to Always:

enter image description here enter image description here Here I've the problem that the tiles behind the mountains are still drawn when they shouldn't, which make sense since it's ignoring z-ordering, and therefore rendering over other objects too.

I've tried using a another shader pass to first write to the z buffer to avoid rendering the tiles behind the mountains with no success. I guess I'm missing something related to the terrain shader, but I have no clue what it may be.

Any help will be much appreciated.


You can use a pixel shader for this.

Pass the size of a single grid square and the radius of a circle to the shader, divide it by the gridSize, round it then multiply by gridSize to get the closest grid point. If the distance between the current fragment and the closest point is less than or equal to the radius, then it's inside the circle:

gX = round(fragX / gridSize) * gridSize
gY = round(fragY / gridSize) * gridSize
d = sqrt((x - gX)^2 + (y - gY)^2)
if (d <= radius)
    color = (0, 1, 0, 1) // green

No postprocessing or addional rendering needed

  • \$\begingroup\$ Yes I studied that possibility, but the tiles won't stay static (this will be a turn based game). The tiles will be colored, lots of possible colors, and adding logic for this in the pixel shader does not seems like a good idea. Also I would prefer not to modify the terrain shader (but won't refuse if it's a solution). \$\endgroup\$ – Celtc Oct 25 '17 at 18:09
  • \$\begingroup\$ Using a additional mesh I use vertex colors for coloring the different tiles (every tile store their vertex indexes for faster modification). This way is quite simple and fast. \$\endgroup\$ – Celtc Oct 25 '17 at 18:31

Your Answer

