ShaderLab学习小结(八)在标准表面shader中加入
场景中新建cube,和一个plane,新建一个standard surface shader和用此shader的材质赋给cube。
在不改变这个标准表面shader原有元素的基础上加入顶点程序,实现”ShaderLab学习小结(七)用插值函数lerp渐变颜色“中的颜色渐变,如下图:
shader代码:
Shader "Custom/TestCarPaintShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness("Smoothness", Range(0,1)) = 0.5 _Metallic("Metallic", Range(0,1)) = 0.0 //1.以下四个属性为新加入的实现渐变色属性(参见学习小结(七)) _Center("Center", range(-120,420)) = 0 _R("R",range(0,400)) = 0 _MainColor("Main Color", color) = (0,0,1,1) _SecColor("Second Color", color) = (1,0,0,1) } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types //#pragma surface surf Standard fullforwardshadows //2. #pragma surface surf Standard vertex:vert //3. // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; float _Center; float _R; struct Input { float2 uv_MainTex; float x; //4. }; half _Glossiness; half _Metallic; fixed4 _Color; fixed4 _SecColor; fixed4 _MainColor; //5. void vert(inout appdata_full v, out Input o) { o.uv_MainTex = v.texcoord.xy; o.x = v.vertex.y; } void surf (Input IN, inout SurfaceOutputStandard o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; //6. float s = IN.x - (_Center - _R / 2); float f = saturate(s / _R); fixed4 col = lerp(_MainColor, _SecColor, f); o.Albedo *= col.rgb; } ENDCG } FallBack "Diffuse"}
如上,代码中用注释标注了六处
1四个属性的声明,这个参见学习小结(七)
2和3//#pragma surface surf Standard fullforwardshadows //2. #pragma surface surf Standard vertex:vert //3.
原来的标准表面shader中用的是2,为了引入顶点程序,改为3
4构造体
struct Input { float2 uv_MainTex; float x; //4. };
参照学习小结(七),要实现x坐标或y坐标方向上的颜色渐变,需要一个值记录坐标,用于计算
5加入顶点函数
//5. void vert(inout appdata_full v, out Input o) { o.uv_MainTex = v.texcoord.xy; o.x = v.vertex.y; }
注意:void,即无返回值,函数的参数变成两个,输出Input o
同样,对o中的元素赋值,o.uv_MainTex,以及o.x。本例还是以y坐标来渐变,所以
6o.x=v.vertex.y;
//6. float s = IN.x - (_Center - _R / 2); float f = saturate(s / _R); fixed4 col = lerp(_MainColor, _SecColor, f); o.Albedo *= col.rgb;
渐变计算,同学习小结(七)。唯一不同的是颜色的设置
o.Albedo,在标准着色器中,o.Albedo赋予的是材质的颜色,即前面
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; o.Albedo = c.rgb;
再和渐变计算出的颜色rgb相乘,得出最终颜色
我们这里没有设置材质贴图,原有的主颜色_Color保持默认的白色,就出来了图中的效果。
且这个shader保留了原有的表面着色器,包括贴图、光照、阴影、smoothness、metallic等属性,是在这些的基础上做出的颜色渐变。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。