unity中如果图片打入了图集中,在shader中取到的uv坐标默认是图集中的坐标,如果需要shader做一些类似流光的效果,需要转换成常用的0-1区间的归一化uv坐标,转换方法如下:
步骤一: C#中向shader中传入图片在图集中的Rect信息和Scale信息
Vector4 UVRect = UnityEngine.Sprites.DataUtility.GetOuterUV(spriteRenderer.sprite);
Rect originRect = spriteRenderer.sprite.rect;
Rect textureRect = spriteRenderer.sprite.textureRect;
float scaleX = textureRect.width / originRect.width;
float scaleY = textureRect.height / originRect.height;
spriteRenderer.material.SetVector("_UVRect", UVRect);
spriteRenderer.material.SetVector("_UVScale", new Vector4(scaleX, scaleY, 0, 0));
步骤二: shader中根据Rect信息和Scale信息换算得到归一化UV坐标:
_UVRect("UVRect", Vector) = (0, 0, 1, 1)
_UVScale("UVScale", Vector) = (0, 0, 0, 0)
//Shader Pass中声明变量属性
float4 _UVRect;
float4 _UVScale;
//Fragment Shader中换算算法,换算后的IN.texcoord就是归一化后的UV坐标
float2 center = (_UVRect.zw - _UVRect.xy) / 2;
IN.texcoord = IN.texcoord - _UVRect.xy - center;
IN.texcoord *= _UVScale;
IN.texcoord += center;
IN.texcoord = IN.texcoord / (_UVRect.zw - _UVRect.xy);