CG shader - World Position, if statement shorthand, frac

The shader below uses world position to create stripes on an object. It's as simple as including worldPos in the Input struct and using IN.worldPos.y or .x or .z.

We're using the shorthand IF statement to assign a green (0,1,0) and red (1,0,0) to the surface where the worldPos.y is less than _rimThreshold. The shorthand is as follows - 

condition ? true result : false result

IN.worldPos.y>0.5 ? float3(0,1,0): float3(1,0,0);

We're also using the frac function here on the worldPos.y - this returns just the fractional part of the number. eg. 3.23 would return just the 0.23 part. so in this example, 0.23 is NOT greather than 0.5, so would return false and therefore the (1,0,0) colour. By multiplying the worldPos.y by 5 (or any number) we're essentially able to repeat the pattern by 5 times. The *0.5 is just a further arbitrary scaling!

Final point - just multiplying the colour by the dot product to give the surface a bit of shape, instead of being flat. Alternatively, you could just swap o.Emission out for o.Albedo - not quite the same, but it would give you shape nevertheless.

 

Shader "Dave/worldPos"
{
    Properties{
        _rimThreshold("rim width",Range(0,10))=0.9
    }
    SubShader{
        CGPROGRAM
        #pragma surface surf Lambert

        struct Input {
            float3 viewDir;
            float3 worldPos;
        };
       
      half _rimThreshold;

    void surf(Input IN, inout SurfaceOutput o) {
        half dotp = 1-dot(IN.viewDir, o.Normal);
        o.Emission = frac(IN.worldPos.y*5*0.5)>_rimThreshold?float3(0,1,0)*dotp:float3(1,0,0)*dotp;


        }


        ENDCG
    }
                 Fallback "Diffuse"
}

Comments

Popular posts from this blog

setting VFX graph properties using C#