1
\$\begingroup\$

I am trying to scroll a texture using its uv in Unity but I don't get the result I need.

The aim is to have two components, the speed and the direction. I would like to define the direction in normalized values and the speed should influence the velocity of the scrolling according to the direction.

If I change the speed at runtime, I don't want to have some hiccups but maybe this should not be handled but the GPU.

How can I do that in a better way, maybe using matrix ?

Here is an example but the result is not as good as expected.

uv.xy = uv.xy + frac(_Time.y * float2(_Direction.x, _Direction.y));
\$\endgroup\$
2
\$\begingroup\$

You can control texture UV with external code. Define uniform float4 _Diffuse_ST; in your shader and then in your script call it every Update():

public float rollSpeed = 0.1f;

void Update()
{
    offset += Time.deltaTime * rollSpeed;
    renderer.material.SetTextureOffset("_Diffuse", new Vector2(offset, 0));
}

Then your shader will look like this (it also rotates the texture, but you can remove this code):

Shader "Custom/TextureRotation"
{
    Properties 
    {
        _Diffuse("_Diffuse", 2D) = "black" {}
    }

    SubShader 
    {                   
        Pass
        {
            CGPROGRAM       

            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0          

            sampler2D _Diffuse;
            float4x4 _Rotation;
            uniform float4 _Diffuse_ST;

            struct vertexInput
            {
                float4 vertex : POSITION;               
                float4 texcoord : TEXCOORD0;               
            };

            struct vertexOutput
            {
                float4 pos : SV_POSITION;
                half2 col : TEXCOORD0;
            };

            struct Input
            {               
                float2 uv_Diffuse;
            };

            vertexOutput vert(vertexInput input)
            {
                vertexOutput output;

                output.pos =  mul(UNITY_MATRIX_MVP, input.vertex);
                output.col =  input.texcoord.xy *_Diffuse_ST.xy + _Diffuse_ST.zw;               
                return output;
            }

            float4 frag (vertexOutput IN) : COLOR
            {           
                float4 MxV0=mul( _Rotation, (IN.col.xyxy) );
                return tex2D(_Diffuse,MxV0.xy);
            }
            ENDCG
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.