うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】オブジェクトの陰色を変更する

オブジェクトの影色を変更する記事はあったが オブジェクトの陰色を変更している記事を見かけなかったため、 調べて色を変更できるようになったのでまとめる

陰とはオブジェクトの光の当たってない部分のことである f:id:hacchi_man:20191128235513p:plain

Vertexだとライトの計算を時前でやる必要があるのでサーフェースシェーダーで作成する

Shader "Custom/Shade" 
{
    Properties 
    {
        _ShadeColor("ShadeColor", Color) = (0.0, 0.0, 0.0)
    }
    
    SubShader 
    {
        Tags { "RenderType"="Opaque" }
        
        CGPROGRAM
        
        #pragma surface surf SimpleLambert 
        
        fixed4 _ShadeColor;
        
        struct Input 
        {
            float2 uv_MainTex;
        };
        
        void surf (Input IN, inout SurfaceOutput o) 
        {
            o.Albedo = fixed4(1.0, 1.0, 1.0, 1.0);
            o.Alpha = 1.0;
        }
        
        fixed4 LightingSimpleLambert (SurfaceOutput s, half3 lightDir, half atten) 
        {
            half NdotL = dot(s.Normal, lightDir);
            return fixed4(lerp(_ShadeColor.rgb, s.Albedo * _LightColor0.rgb, max(0, NdotL)), s.Alpha);
        }
        ENDCG
    }
    
    FallBack "Mobile/Diffuse"
}

もともとのLambert処理は

half4 LightingSimpleLambert (SurfaceOutput s, half3 lightDir, half atten) 
{
    half NdotL = dot (s.Normal, lightDir);
    half4 c;
    c.rgb = s.Albedo * _LightColor0.rgb * (NdotL * atten);
    c.a = s.Alpha;
    return c;
}

となっており、光の向きと逆の場合にShadeColorの割合を多くしてやることで陰色を変更できる。

このシェーダーを適応すると

f:id:hacchi_man:20191129004817p:plain

のようになり陰色が変更できている。