Skip to content

Instantly share code, notes, and snippets.

@abstractron
Created January 18, 2018 20:13
Show Gist options
  • Save abstractron/7819242cb2c05d9f57803e9d13249292 to your computer and use it in GitHub Desktop.
Save abstractron/7819242cb2c05d9f57803e9d13249292 to your computer and use it in GitHub Desktop.
Unity grid floor shader
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
Shader "Custom/GridShader" {
Properties{
_GridThickness("Grid Thickness", Float) = 0.1
_GridSpacing("Grid Spacing", Float) = 0.1
_GridColour("Grid Colour", Color) = (0.5, 1.0, 1.0, 1.0)
_BaseColour("Base Colour", Color) = (0.0, 0.0, 0.0, 0.0)
}
SubShader{
Tags{ "Queue" = "Transparent" }
Pass{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
// Define the vertex and fragment shader functions
#pragma vertex vert
#pragma fragment frag
// Access Shaderlab properties
uniform float _GridThickness;
uniform float _GridSpacing;
uniform float4 _GridColour;
uniform float4 _BaseColour;
// Input into the vertex shader
struct vertexInput {
float4 vertex : POSITION;
};
// Output from vertex shader into fragment shader
struct vertexOutput {
float4 pos : SV_POSITION;
float4 worldPos : TEXCOORD0;
};
// VERTEX SHADER
vertexOutput vert(vertexInput input) {
vertexOutput output;
output.pos = UnityObjectToClipPos(input.vertex);
// Calculate the world position coordinates to pass to the fragment shader
output.worldPos = mul(unity_ObjectToWorld, input.vertex);
output.worldPos.x -= _GridThickness/2;
output.worldPos.z -= _GridThickness/2;
return output;
}
// FRAGMENT SHADER
float4 frag(vertexOutput input) : COLOR{
if (frac(input.worldPos.x / _GridSpacing) < _GridThickness || frac(input.worldPos.z / _GridSpacing) < _GridThickness) {
return _GridColour;
}
else {
return _BaseColour;
}
}
ENDCG
}
}
}
@tobischw
Copy link

Is there a way to force a certain amount of cells instead of it indefinitely repeating? Either way, thank you, this was very useful!

@SpaceWarpStudio
Copy link

SpaceWarpStudio commented Feb 11, 2019

Noticed a bug, if you wish to center the grids over the center of the object position, as I believe this is trying to achieve...

output.worldPos.x -= _GridThickness / 2;
output.worldPos.z -= _GridThickness / 2;

.. This should be += rather than -=, and then is only accurate when the grid spacing is 1 (meter). For higher amounts you need...

output.worldPos.x += _GridThickness / 2 * _GridSpacing;
output.worldPos.z += _GridThickness / 2 * _GridSpacing;

Edit: Clarification / error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment