Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Add fresnel effect to fragment shader

Discussion in 'Shaders' started by SUBZERO8K, Jan 18, 2018.

  1. SUBZERO8K

    SUBZERO8K

    Joined:
    Jan 15, 2013
    Posts:
    36
    Hi there, I am trying to add a fresnel/rim effect to a fragment shader, but am encountering some issues in getting the correct rim color to apply.

    Code (CSharp):
    1. fixed4 frag (v2f i) : SV_Target
    2.             {
    3.                 // Sample texture
    4.                 half4 col = tex2D(_MainTex, i.uv) * _Tint; // Texture times tint color;
    5.  
    6.                 // View direction of camera
    7.                 float3 viewDir = normalize(_WorldSpaceCameraPos - i.worldPos);
    8.                 half rim = 1.0 - saturate(dot(normalize(viewDir), i.normal));
    9.                 half4 newCol = half4(col * _RimColor);
    10.                 newCol.a = col.a;
    11.                 newCol *= pow(rim, _RimPower);
    12.                 col = newCol;
    13.  
    14.                 return col;
    15.             }
    This snippet seems to apply the fresnel effect correctly, but the rim color isn't displaying correctly. The rim color appears as black in-game regardless of what color I set it to in the inspector. Does anyone have any insight as to what I'm doing wrong here? Thanks!

    Screen Shot 2018-01-18 at 9.17.23 AM.png
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,248
    What exactly are you expecting? You're multiplying your texture by the tint color, the rim color, and by the inverted dot product. That's a lot of multiplying.

    I suspect you really want a lerp in there someplace, but it depends on what the final look you're going for is.

    half rim = 1.0 - saturate(dot(normalize(viewDir), i.normal));
    col.rgb = lerp(col.rgb, col.rgb * _RimColor.rgb, pow(rim, _RimPower));
     
    SUBZERO8K likes this.
  3. SUBZERO8K

    SUBZERO8K

    Joined:
    Jan 15, 2013
    Posts:
    36
    Thanks, this is indeed the look I was trying to get.