Distance to camera

I am a newbie in programming shaders… I want to calculate the distance between camera and the object (attached shader). I found something like this…

float curDistance = distance(_CentrePoint.xyz, IN.worldPos);

my shader looks like this…

Shader "Custom/VertexColor" {

Properties {
         _PointSize ("Point Size", Float) = 1
     }

    SubShader {
    Pass {
        LOD 200
             
                
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        float _PointSize;
      
 
        struct VertexInput {
            float4 v : POSITION;
            float4 color: COLOR;

        };
        
        struct VertexOutput {
            float4 pos : SV_POSITION;
            float4 col : COLOR;
            float4 size : PSIZE;
        };
        
        VertexOutput vert(VertexInput v) {        
            VertexOutput o;
            o.pos = mul(UNITY_MATRIX_MVP, v.v);
            o.col = v.color;
            o.size = _PointSize;
            return o;
        }
        
        float4 frag(VertexOutput o) : COLOR {
            return o.col;
        }
        ENDCG
        }
    }
}

You need to calculate the world space vertex position in the vertex shader and pass that to the fragment shader. There are some examples of this in the vert / frag shader examples here:

Look for “worldPos”.

Then you just need to do that distance check against the camera position which is already passed to all shaders as _WorldSpaceCameraPos.

Alternatively you can calculate the view space vertex position and pass that to the fragment shader and then just do length( i.viewPos). It’s calculated the same way as the world pos just using UNITY_MATRIX_MV instead of _Object2World.