Hi Everyone.
I’m modifying default shader script and found out that uv’s there are not normalized because SpriteRenderer probably renders only 1 tile from a sprite sheet.
How can I convert UV’s to make them normalized ([0…1])?
I totally stuck with _MainTex_TexelSize and _MainTex_ST conversation.
v2f vert(appdata_t IN) {
v2f OUT;
OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif
return OUT;
}
fixed4 frag(v2f IN) : COLOR {
half2 p = IN.texcoord.xy;
fixed4 c = tex2D(_MainTex, p) * IN.color;
...
}
So, here p - is not normalized and I wanna make it normalized (that p.x and p.y will go from 0 to 1).
Please, help.
1 Like
I figured out a way to do this by encoding the atlased UV and the normalised UV into the same float2.
so, if the normal sprite atlased uv’s looked like this:
0.25,0.25
0.25,0.75
0.75,0.75
0.75,0.25
the equivalent new uv’s (with the normalised UV embedded) would look like this:
1.25,1.25
1.25,2.75
2.75,2.75
2.75,1.25
here is the code:
v2f vert(appdata_t IN)
{
v2f OUT;
UNITY_SETUP_INSTANCE_ID(IN);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
OUT.worldPosition = IN.vertex;
OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);
float4 uvs = ExtractUVs(IN.texcoord); // Extract both UV and normalised UV from a single float2
OUT.texcoord = uvs.xy; // pass on the atlased UV to the pixel shader
OUT.normalisedtexcoord = uvs.zw; // pass on the normalised UV to the pixel shader
OUT.color = IN.color * _Color;
return OUT;
}
// Extract UV and Normalised UVs into a float4… 
float4 ExtractUVs(float2 uv0)
{
uv0 -= float2(1.0,1.0);
float4 uv1 = uv0.xyxy;
if (uv1.x > 1.0)
uv1.x -= 1.0;
if (uv1.y > 1.0)
uv1.y -= 1.0;
uv1.zw -= uv1.xy;
return uv1; // uv1.xy = UV and uv1.zw = NormalisedUVs
}
Enjoy.