2

I want to map a 2D Texture onto a procedurally generated plane, using vertex local position, in Unity. This is the code:

Shader "Custom/planeTest"
{
Properties
{
    _MainTex("Albedo (RGB)", 2D) = "white" {}
    _Scale("Scale of texture", Vector) = (0.0, 0.0, 0.0)
    _Offset("Offset of texture", Vector) = (0.0, 0.0, 0.0)
}

SubShader
{
    CGPROGRAM

    #pragma surface surf Standard vertex:vert
    #pragma target 3.0

    sampler2D _MainTex;
    float3 _Scale;
    float3 _Offset;

    struct Input {
        float2 uv_MainTex;
    };

    void vert(inout appdata_full v, out Input o)
    {
        UNITY_INITIALIZE_OUTPUT(Input, o);
        o.uv_MainTex = mul(unity_ObjectToWorld, v.vertex).xz;
    }

    void surf(Input IN, inout SurfaceOutputStandard o)
    {
        float2 _uv = (IN.uv_MainTex.x * _Scale.x, IN.uv_MainTex.y * _Scale.y) + _Offset.xy;
        o.Albedo = tex2D(_MainTex, _uv).rgb;
    }

    ENDCG
}

Fallback "Diffuse"
}

I don't understand why, but this makes the plane's color uniform. The only option I can use is _Offset, that changes the color of the entire plane. I think (IN.uv_MainTex.x * _Scale.x, IN.uv_MainTex.y * _Scale.y) it's always zero, but I don't understand why.

Please help me understanding what I'm doing wrong

Gugu
  • 73
  • 7
  • 1
    I think you meant to say `float2 _uv = float2(IN.uv_MainTex.x ...`. You can also write componentwise multiplication like `float2 _uv = IN.uv_MainTex*_Scale.xy +_Offset.xy` – Pluto Dec 07 '17 at 17:33
  • Thanks, I didn't know it! – Gugu Dec 07 '17 at 17:41

1 Answers1

0

Check https://docs.unity3d.com/Manual/SL-SurfaceShaders.html under "Surface Shader input structure"

uv_MainTex is automatically generated, so setting it manually might create some problems. You might want to use another custom name in your input struct.

Side note: you should do all your arithmetic in the vertex shader, since they are all linear transformations anyway.

Brice V.
  • 861
  • 4
  • 7