UnityShader学习教程之<根据透明阴影图扭曲图片(褶皱)>

最近由于工作需要,研究了一个效果,起初考虑用shader实现,因此写了下面的代码:
这里写图片描述

			fixed4 frag (v2f i) : SV_Target 
			{
			    float2 uvcenter = float2(0.5,0.5);
				float2 uvdiffuse = mul(float2x2(_Reseapt,0,0,_Reseapt),i.uv)+ uvcenter;

				float4 alpha = tex2D(_Alpha,TRANSFORM_TEX(i.uv,_Alpha));
				alpha.a-=_A;
				float2 uv;
				if(alpha.a > 0)
				{
				   float x = uvdiffuse.x * (pow(alpha.a/_F,_P)+_X);
				   float y = uvdiffuse.y * (pow( alpha.a/_F,_B)+_Y);
				   uv = float2(x,y);
				}
				if(alpha.a<=0)
				{
				   uv = uvdiffuse;
				}
				fixed4 col = tex2D(_MainTex,TRANSFORM_TEX(uv,_MainTex))*_Power;	
				return col;
			}

这是shader实现的核心代码,效果如上:
鉴于需求,还需要有c#实现的方法,于是研究了一套方法,实现的效果如下:
这里写图片描述
核心代码如下:

    /// <summary>
    /// 处理不同部位的图片
    /// </summary>
    /// <param name="tex2D">传入的部位图</param>
    /// <param name="rotation">图片旋转的参数</param>
    /// <returns></returns>
    Texture2D ChangeTextrue(Texture2D tex2D,float rotation,float transformX,float transformY)
    {
        //对面料图进行旋转操作
        Texture2D texc = new Texture2D(_textrueCloth.width, _textrueCloth.height);
        texc = RotateTexture(_textrueCloth, rotation);
        texc = TransfromTextrue(texc, transformX, transformY);

        //根据阴影图进行扭曲操作
        Texture2D tex = new Texture2D(_textruegray.width, _textruegray.height);
        for (int i = 1; i <= _textruegray.width; i++)
        {
            for (int j = 1; j <= _textruegray.height; j++)
            {
                //拿到灰度图的alpha值
                Color alpha = _textruegray.GetPixel(i, j);
                alpha.a -= 22;
                //求得采样的uv坐标
                float u = i * Mathf.Pow(alpha.a / _Twist, _PowScaleU);
                float v = j * Mathf.Pow(alpha.a / _Twist, _PowScaleV);
                //根据alpha的a值对图片的所有像素点进行赋值
                if (alpha.a > 0)
                {
                    //如果一样则不做偏移
                    Color texcolor = texc.GetPixel(i, j);
                    tex.SetPixel(i, j, texcolor);
                }
                else
                {
                    Color texcolor = texc.GetPixel((int)u, (int)v);
                    tex.SetPixel(i, j, texcolor);
                }
            }
        }
        Texture2D texfinel = new Texture2D(_textruegray.width, _textruegray.height);
        //根据传入的位置图片,出来当前的最终合成图
        for (int m = 1; m <= _textruegray.width; m++)
        {
            for (int n = 1; n < _textruegray.height; n++)
            {
                Color col = tex.GetPixel(m, n);
                Color acolor = tex2D.GetPixel(m, n);
                texfinel.SetPixel(m, n, new Color(col.r, col.g, col.b, acolor.a));
            }
        }
        texfinel.Apply();        
        return texfinel;       
    }

这里没有过多的解释,大家耐心看看吧!!

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页