通过uv坐标变换显示小图
Shader "Unlit/Countertest"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Row("row",Int) = 3 //行
_Col("col",Int) = 4 //列
_Num("number",Float) = 3.0
//_ColIndex ("Col Index", int) = 0
//_RowIndex ("Row Index", int) = 0
}
SubShader
{
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
int _Row;
int _Col;
float _Num;
int _ColIndex;
int _RowIndex;
float fmodfun(float a, float b) //因为性能问题需手动实现fmod()和round()函数
{
float result;
result = a - floor(a/b)*b;
return result;
}
int roundfun(float x)
{
int resultx;
int temp;
temp = step(frac(x), 0.5);
resultx = x - frac(x) + 1 - temp;
return resultx;
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
/*
o.uv = v.uv;
float sourceX = 1.0 / _Col;
float sourceY = 1.0 / _Row;
o.uv.x*= sourceX;
o.uv.y*= sourceY
float LiftOffset=floor(_Num);
float StartY = floor(_Num/4)+1;
float len = fmod(floor(LiftOffset),floor(_Col)) ;
o.uv.x+= len * sourceX;
o.uv.y+= (_Row -StartY) * sourceY;//0~3
*/
/*
float rowindex = floor(_Num / _Row);
float colindex = floor(_Num / _Col);
o.uv.x = (colindex + v.uv.x) / _Col;
o.uv.y = (rowindex + v.uv.y) / _Row;
return o;
*/
float totaltile = _Col*_Row;
float coloffset = 1.0f/_Col;
float rowoffset = 1.0f/_Row;
float2 tiling = float2(coloffset,rowoffset);
float currentindex = roundfun(fmodfun(_Num,totaltile));
float indextox = roundfun(fmodfun(currentindex,_Col));
float offsetx = indextox*coloffset;
float indextoy = roundfun(fmodfun((currentindex - indextox)/_Col,_Row));
indextoy = _Row - 1 - indextoy;
float offsety = indextoy*rowoffset;
o.uv = o.uv*tiling+float2(offsetx,offsety);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
return col;
}
ENDCG
}
}
}
最终效果: