Simple World Triplanar Grid (Allows Transparency)
I use grid shaders for a lot of my projects so I wanted to save this one cause is quite simple.
Features:
- Adjustable line width and grid size (The grid follows the editor one by default).
- Color customization that allows transparency.
- Triplanar mapping calculated based on the world position of the objects, ensuring consistency across the scene regardless of position.
How to use:
- Create a new shader material and a new shader script and paste this code in the script.
- Adjust the shader parameters to achieve the desired grid appearance, it follows the grid editor by default.
- Apply the material to the mesh instances in your scene to see the triplanar grid effect in action.
P.D.: I used github copilot to make this. Feel free to comment fixes for this and I will try to update it.
Shader code
shader_type spatial;
uniform float line_width : hint_range(0.0, 1.0) = 0.04;
uniform float grid_size : hint_range(0.0, 10.0) = 1.0;
uniform vec4 line_color : source_color = vec4(1.0, 1.0, 1.0, 1.0);
uniform vec4 fill_color : source_color = vec4(0.0, 0.0, 0.0, 1.0);
void fragment() {
// Calculate world position
vec3 world_pos = (INV_VIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
// Apply grid effect
vec2 grid_pos = mod(world_pos.xz + grid_size * 0.5, grid_size) / grid_size - 0.5;
grid_pos = abs(grid_pos) * 2.0;
float line = min(step(line_width, grid_pos.x), step(line_width, grid_pos.y));
// Apply color and transparency
ALBEDO = mix(line_color.rgb, fill_color.rgb, line);
ALPHA = mix(line_color.a, fill_color.a, line);
}