Search Unity

Texture UV animation in GLSL.

Discussion in 'Shaders' started by melong, Sep 11, 2011.

  1. melong

    melong

    Joined:
    Sep 2, 2011
    Posts:
    22
    Hi everyone,

    I tried to write a GLSL shader that can translate the UV coordinates according to a vector. Here's what i've got so far :
    Code (csharp):
    1. Shader "MyShaders/TextureUvAnimation"
    2.  
    3. {
    4.  
    5.     Properties
    6.  
    7.     {
    8.  
    9.         _MainTex("Texture Color", 2D) = "black"
    10.  
    11.         _DirectionUv("Texture scroll direction", Vector) = (1,1,0,0)
    12.  
    13.     }
    14.  
    15.    
    16.  
    17.     SubShader
    18.  
    19.     {      
    20.  
    21.         Pass
    22.  
    23.         {          
    24.  
    25.             GLSLPROGRAM
    26.  
    27.            
    28.  
    29.                 uniform vec4 _Time;
    30.  
    31.                
    32.  
    33.                 varying mediump vec2 uv;
    34.  
    35.                
    36.  
    37.                 uniform mediump sampler2D _MainTex;
    38.  
    39.                 uniform mediump vec4 _DirectionUv;
    40.  
    41.    
    42.  
    43.                 #ifdef VERTEX
    44.  
    45.                     void main()
    46.  
    47.                     {
    48.  
    49.                         uv = gl_MultiTexCoord0.xy + _Time.xx * _DirectionUv.xy;
    50.  
    51.                         gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
    52.  
    53.                     }
    54.  
    55.                 #endif
    56.  
    57.    
    58.  
    59.                 #ifdef FRAGMENT
    60.  
    61.                     void main()
    62.  
    63.                     {
    64.  
    65.                         vec4 TextureColor = texture2D(_MainTex, uv);
    66.  
    67.  
    68.  
    69.                         gl_FragColor = TextureColor;
    70.  
    71.                     }
    72.  
    73.                 #endif  
    74.  
    75.             ENDGLSL
    76.  
    77.         }
    78.  
    79.     }
    80.  
    81. }
    This is working as expected but now i'm wondering what will happen when the variable "uv" will reach its limit (since it is growing constantly as long as the _Time function goes on) ?
    If i want the texture to loop endlessly, i guess i need to reset the UV coordinates to their original position each time "_time.xx*_DirectionUv.xy" reaches 1 and this is where i'm stuck. Does anyone know how i could do that ?
     
  2. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
  3. melong

    melong

    Joined:
    Sep 2, 2011
    Posts:
    22
    Indeed, that's easier than i have expected. Thanks a lot !