Hello everyone!
I am completely new to Unity Shaders and have a question regarding rotation. I found a grid shader in this thread: wireframe grid shader , but I wanted it to behave different than it does. The shader draws a grid in world space, what I wanted was that the grid is drawn in object space so that I can use the Shader on a Quad object that I can scale and rotate.
If I scale the square, the grid should simply be repeated further. And when I rotate the square, the grid should rotate and keep its structure.
I’ve managed to make the scaling behave the way I want it to. However, the squares change to rectangles when I rotate the Quad.
All I changed was to take the local coordinates of the vertex instead of the world coordinates. Then I multiplied the scaling of the Quad with the denominator for the coordinate in the fragment shader.
Shader "Grid" {
Properties{
_GridThickness("Grid Thickness", Float) = 0.01
_GridSpacing("Grid Spacing", Float) = 10.0
_GridColour("Grid Colour", Color) = (0.5, 0.5, 0.5, 0.5)
_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 localPos : 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.localPos = input.vertex; // mul(unity_ObjectToWorld, input.vertex);
return output;
}
// FRAGMENT SHADER
float4 frag(vertexOutput input) : COLOR {
if (frac(input.localPos.x / _GridSpacing * length(unity_ObjectToWorld._m00_m01_m20)) < _GridThickness || frac(input.localPos.y / _GridSpacing * length(unity_ObjectToWorld._m01_m11_m21)) < _GridThickness) {
return _GridColour;
}
//else
// if (frac(input.worldPos.x / _GridSpacing * length(unity_ObjectToWorld._m00_m01_m20)) < _GridThickness || frac(input.worldPos.z / _GridSpacing * length(unity_ObjectToWorld._m02_m12_m22)) < _GridThickness) {
// return _GridColour;
// }
else {
return _BaseColour;
}
}
ENDCG
}
}
}
Can anyone explain what I have to do to make the rotation works so that the squares stay squares? And give me the reason why it behaves like it does?


