How to do simple shader

Suppose I have a NxN texture.

For each pixel (i,j), if i+j is even, I want that pixel to be black, otherwise it must be white.

How can I do such shader?

Shader "Debug/UV 1" {
SubShader {
    Pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        // vertex input: position, UV
        struct appdata {
            float4 vertex : POSITION;
            float4 texcoord : TEXCOORD0;
        };

        struct v2f {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
        };
       
        v2f vert (appdata v) {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex );
            o.uv = float4( v.texcoord.xy, 0, 0 );
            return o;
        }
       
        half4 frag( v2f i ) : SV_Target {
            if ((i.x == i.y))
                return 0;
            else return 1;

        }
        ENDCG
    }
}
}

Like this?

Haven’t tested yet.

who is i.x and i.y? there isn’t definition for them in struct v2f

anyways I think this is wrong, you are using (x == y) but it should be something like (x + y == 2n)

v2f vert (appdata v) {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex );
            o.uv = float4( v.texcoord.xy, 0, 0 );
            return o;
        }
      
        half4 frag( v2f i ) : SV_Target {
            float current = tex2D(_Texture, i.uv).r; // red channel holds relevant data
           float next = tex2D(_Texture, i.uv + float2(1/_TextureSize, 0)).r;
          float remainder = fmod(current + next, 2);

         return remainder == 0 ? 1 : 0;
        }

The above is code pointing in the general direction.
You need to define a sampler for your texture and probably a property, too (named _Texture in the above code).
1/_TextureSize for example is something that you can get from internal Unity variables which I do not know the name of at the moment - I made it up. Also: 1/_TextureSize might not end up in the middle of the texel, so you may need to adjust it with a halftexel offset.
The returned term at the end of the fragment shader needs to be of float4 - in my case it is just a scalar value.
Hope this helps to get you started.

1 Like