Search Unity

Height fading 2D with Atlas

Discussion in 'Shaders' started by lordubik, Sep 8, 2021.

  1. lordubik

    lordubik

    Joined:
    Feb 18, 2013
    Posts:
    149
    Hi, we had try to make a shader to apply a height fading to an animated sprite. The trouble is that the sprites are inside the atlas and we cannot use uv directly so we convert the UV inside pixel shader to 0,1 with a rect set from a behaviour.

    Inside behaviour:

    Code (CSharp):
    1.     public void SetUV()
    2.     {
    3.         Rect rect = spriteRenderer.sprite.textureRect;
    4.         rect.x /= spriteRenderer.sprite.texture.width;
    5.         rect.width /= spriteRenderer.sprite.texture.width;
    6.         rect.y /= spriteRenderer.sprite.texture.height;
    7.         rect.height /= spriteRenderer.sprite.texture.height;
    8.  
    9.         if(render)
    10.         {
    11.             render.sharedMaterial.SetFloat("_min_x_uv", rect.xMin);
    12.             render.sharedMaterial.SetFloat("_max_x_UV", rect.xMax);
    13.             render.sharedMaterial.SetFloat("_min_y_UV", rect.yMin);
    14.             render.sharedMaterial.SetFloat("_max_y_UV", rect.yMax);
    15.         }
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         this.SetUV();
    22.     }
    inside shader (frag):

    Code (JavaScript):
    1.             float4 frag (v2f i) : SV_Target
    2.             {
    3.                 float2 uvRect = i.uv0;
    4.                 float u = (i.uv0.x - _min_x_UV) / (_max_x_UV - _min_x_UV);
    5.                 float v = (i.uv0.y - _min_y_UV) / (_max_y_UV - _min_y_UV);
    6.                 uvRect = half2(u, v);
    7.                 float t = uvRect.y;
    8.                 fixed4 c = tex2D(_MainTex, i.uv0) * i.col;
    9.                 return fixed4(_Color.rgb, c.a * t);
    10.             }
    the result is wrong, because the fading from 0 to 1.0 change by current frame.
    attached the result.
    any idea to fix this trouble?

    Thanks for support!

    Stefano
     

    Attached Files:

  2. lordubik

    lordubik

    Joined:
    Feb 18, 2013
    Posts:
    149
    OK, SOLVED (we hope)
    we have use LateUpdate instead Update!

    Stefano