Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Shader "Custom/HexGrid"
- {
- Properties
- {
- _LineWidth ("Line Width", Range(0.001, 0.5)) = 0.05
- _OutlineColor ("Outline Color", Color) = (1, 1, 1, 1)
- _BackgroundColor ("Background Color", Color) = (0, 0, 0, 0)
- _GridScale ("Grid Scale", Float) = 0.2
- }
- SubShader
- {
- Tags
- {
- "RenderType"="Transparent" "Queue"="Transparent"
- }
- LOD 100
- Blend SrcAlpha OneMinusSrcAlpha
- ZWrite Off
- Pass
- {
- CGPROGRAM
- #pragma vertex vert
- #pragma fragment frag
- #include "UnityCG.cginc"
- struct appdata
- {
- float4 vertex : POSITION;
- float2 uv : TEXCOORD0;
- };
- struct v2f
- {
- float2 uv : TEXCOORD0;
- float4 vertex : SV_POSITION;
- float3 worldPos : TEXCOORD1;
- };
- float _LineWidth;
- float4 _OutlineColor;
- float4 _BackgroundColor;
- float _GridScale;
- // Base scale factor to make hexagons = 10 units flat-to-flat
- static const float BASE_SCALE = 10.0;
- // Fixed hex size (always 1.0 now)
- static const float HEX_SIZE = 1.0;
- v2f vert(appdata v)
- {
- v2f o;
- o.vertex = UnityObjectToClipPos(v.vertex);
- o.uv = v.uv;
- o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
- return o;
- }
- // Helper vector for flat-top hex calculations
- float2 getS()
- {
- return float2(1.7320508, 1); // Always flat-top
- }
- // Hexagon distance function
- float hex(float2 p)
- {
- p = abs(p);
- float2 s = getS();
- return max(dot(p, s * 0.5), p.y); // Flat top hexagon
- }
- // Get the hexagon cell coordinate and ID
- float4 getHex(float2 p)
- {
- float2 s = getS();
- // For flat-top hexagons
- float4 hC = floor(float4(p, p - float2(1, 0.5)) / s.xyxy) + 0.5;
- // Centering coordinates with hexagon centers
- float4 h = float4(p - hC.xy * s, p - (hC.zw + 0.5) * s);
- // Return nearest hexagon center and its ID
- return dot(h.xy, h.xy) < dot(h.zw, h.zw) ? float4(h.xy, hC.xy) : float4(h.zw, hC.zw + 0.5);
- }
- fixed4 frag(v2f i) : SV_Target
- {
- // Use world coordinates centered at (0,0,0)
- float2 baseCoord = i.worldPos.xz;
- // Scale coordinates for grid spacing, accounting for the BASE_SCALE factor
- float2 p = baseCoord / _GridScale * BASE_SCALE;
- // Get hexagon cell data with fixed size of 1.0
- float4 h = getHex(p / HEX_SIZE) * HEX_SIZE;
- // Calculate edge distance
- float eDist = hex(h.xy) / HEX_SIZE;
- // Calculate line boundary with minimal antialiasing for crisp edges
- float innerEdge = HEX_SIZE * 0.5 - _LineWidth;
- // Use very small antialiasing range controlled by sharpness
- float outline = 1.0 - smoothstep(innerEdge, innerEdge, eDist);
- // Blend between background color and outline color
- fixed4 finalColor = lerp(_BackgroundColor, _OutlineColor, outline);
- finalColor.a = max(outline * _OutlineColor.a, _BackgroundColor.a * (1.0 - outline));
- return finalColor;
- }
- ENDCG
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment