Search Unity

Rotate Texture through shader for scaled planes

Discussion in 'Shaders' started by shekhar331, Feb 17, 2019.

  1. shekhar331

    shekhar331

    Joined:
    Nov 11, 2014
    Posts:
    10
    Hello,

    I am trying to rotate the texture via shader code. I am able to rotate the texture if the plane is uniformaly scale and the the texture is square one. The shader fails t work when the Texture is a rectangular one and the Plane is generated at runtime (ARCore plane generation)

    Code (CSharp):
    1. Shader "Custom/RotateUVs" {
    2.         Properties {
    3.             _MainTex ("Base (RGB)", 2D) = "white" {}
    4.             _Color ("Alpha", Color) = (1,1,1,1)
    5.             _RotationSpeed ("Rotation Speed", Float) = 2.0
    6.         }
    7.         SubShader {
    8.             Tags { "RenderType"="Transparent" "Queue" = "Transparent" }
    9.             LOD 200
    10.        
    11.             CGPROGRAM
    12.             #pragma surface surf Lambert vertex:vert
    13.  
    14.             sampler2D _MainTex;
    15.             float4 _Color;
    16.  
    17.             struct Input {
    18.                 float2 uv_MainTex;
    19.             };
    20.  
    21.             float _RotationSpeed;
    22.             void vert (inout appdata_full v) {
    23.                 v.texcoord.xy -=0.5;
    24.                 float s = sin ( _RotationSpeed  );
    25.                 float c = cos ( _RotationSpeed  );
    26.                 float2x2 rotationMatrix = float2x2( c, -s, s, c);
    27.                 rotationMatrix *=0.5;
    28.                 rotationMatrix +=0.5;
    29.                 rotationMatrix = rotationMatrix * 2-1;
    30.                 v.texcoord.xy = mul ( v.texcoord.xy, rotationMatrix );
    31.                 v.texcoord.xy += 0.5;
    32.             }
    33.  
    34.             void surf (Input IN, inout SurfaceOutput o) {
    35.                 half4 c = tex2D (_MainTex, IN.uv_MainTex);
    36.                 o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb * 1;
    37.                 o.Albedo *=  _Color.rgb;
    38.                 o.Alpha = _Color.a;
    39.             }
    40.             ENDCG
    41.         }
    42.         FallBack "Diffuse"
    43.     }
    RotateUVSheared.PNG

    Need help to rotate it uniformly.

    Thank you
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    The problem is the UV themselves aren’t square when being rotated. You need to scale down the UVs so that they are square, rotate, then scale back up. I know nothing about how the quad is being generated, but assuming it’s being scaled by the texture dimensions, you’ll have to calculate the inverse scale in the shader based on the texture’s aspect ratio.
     
    kankane likes this.