Unity Shader 实现图片切割部分显示(数字切换)

通过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
		}
	}
}

最终效果:
可以手动输入切换数字

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值