Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Calculate "in line" factor in surface shader

Discussion in 'Shaders' started by sylon, May 15, 2019.

  1. sylon

    sylon

    Joined:
    Mar 5, 2017
    Posts:
    246
    Today my Vector math is hopeless. Focus problem i think.

    I am trying to calculate when a vertex is between my camera and my lightpos.
    Doing this in the vertex prog.
    Code (CSharp):
    1.  
    2. o.worldPos = mul(unity_ObjectToWorld, v.vertex);
    3.  
    4. float3 pointDir=normalize(_WorldSpaceLightPos0.xyz-o.worldPos.xyz);
    5. float3 viewDir = normalize(UnityWorldSpaceViewDir(o.worldPos));
    6. float camDot= dot(viewDir,pointDir)* 0.5 + 0.5;
    7.  
    But i am doing something wrong and i can't figure it out no matter what i try.
    I can't be the first trying this, so i thought i'd ask for help :)
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    What kind of light? If it's a directional light, then _WorldSpaceLightPos0.xyz is already a normalized world space direction. If it's a point light the above is correct, but I'd wonder about the rest of your shader (ie: are you trying to do this in a surface shader or ForwardBase pass).

    Otherwise the rest looks correct.
     
  3. sylon

    sylon

    Joined:
    Mar 5, 2017
    Posts:
    246
    It's a directional light and just a surface shader.
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Then it should just be:

    float camDot = dot(normalize(UnityWorldSpaceViewDir(worldPos), _WorldSpaceLightPos.xyz);

    I think -1 should be directly at the light, 1 directly away. Negate the light or view dir if you want 1 to be toward the light.
     
  5. sylon

    sylon

    Joined:
    Mar 5, 2017
    Posts:
    246
    I think that was the one combination of instructions that i hadn't tried.
    Thank you. a weight has been lifted :)