Search code examples
unity-game-engineshaderfragment-shader

I can't understand the result of my fragment shader


I'm very newbie at unity shader programming. And I've tried some lines of Shader codes. But I couldn't understand the result of it.

Here's my shader codes.

Shader "Test/MyShader"{
Properties
{}

SubShader
{
    Tags { "RenderType"="Opaque" }
    LOD 100

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        struct vertInput
        {
            float4 vertex : POSITION;
        };

        struct fragInput
        {
            float4 vertex : SV_POSITION;
        };

        fragInput vert (vertInput IN)
        {
            fragInput o;
            o.vertex = UnityObjectToClipPos(IN.vertex);
            return o;
        }

        fixed4 frag (fragInput IN) : SV_Target
        {
            return fixed4(IN.vertex);
        }
        ENDCG
    }
}

}

I applied this shader code to the normal Plane. I expected the result to be seemed like spectrums. But what I've got is very different from what I've expected.

Here's the image link.

And this is Plane's inspector info.

Can anyone explain why this result come out?


Solution

  • As I understand, you expect, that color will depend on pixel position on the screen. To make it you should know what is result of UnityObjectToClipPos(IN.vertex);. And the reslut will be a vector, that contains

    • x = pixel X coordinate on screen in range [0, ScreenWidthInPixels]
    • y = pixel Y coordinate on screen in range [0, ScreenHeightInPixels]
    • z = 0
    • w = distance to the object in this pixel

    And in your example you try to somehow map it to color vector, thats elements should be in range [0, 1]. So as result this color will be the same as if you specify color (1.0, 1.0, 0, 1.0). To receive some sanity result you shold make your fragment shader looks like this or something:

    fixed4 frag (fragInput IN) : SV_Target
            {
                //IN.vertex.w contains distance from camera to the object
                return fixed4(IN.vertex.x / _ScreenParams.x, IN.vertex.y / _ScreenParams.y, 0.0, 1.0);
            }
    

    And the result will be like:

    enter image description here

    Usefull links: