Unity Shader 纹理映射的实现
1 // 纹理映射的编写 2 Shader "TMoon/04-Texture" { 3 Properties{ 4 _Color("Color",Color) = (1,1,1,1) 5 _MainTex("Main Tex",2D) = "white"{} 6 } 7 8 SubShader{ 9 10 Pass{ 11 12 Tags {"LightMode" = "ForwardBase"} 13 14 CGPROGRAM 15 16 #include "Lighting.cginc" 17 18 #pragma vertex vert 19 #pragma fragment frag 20 21 fixed4 _Color; 22 sampler2D _MainTex; 23 float4 _MainTex_ST; //命名必须根据_MainTex 这里自动匹配面板的Tiling和Offset 24 25 // application to vertex 26 // 由应用程序传递给顶点函数 27 struct a2v { 28 float4 vertex:POSITION; 29 float3 normal:NORMAL; 30 float4 texcoord:TEXCOORD0; // 模型的纹理坐标 31 }; 32 33 // vertex to fragment 34 // 由顶点函数传递给片元函数 35 struct v2f { 36 float4 svPos:SV_POSITION; 37 float3 worldNormal:TEXCOORD0; 38 float4 worldVertex:TEXCOORD1; 39 float2 uv:TEXCOORD2; 40 }; 41 42 v2f vert(a2v v) { 43 v2f f; 44 45 f.svPos = mul(UNITY_MATRIX_MVP, v.vertex); 46 f.worldNormal = normalize(UnityObjectToWorldNormal(v.normal)); 47 // 将模型空间的顶点坐标变换到世界空间上 48 f.worldVertex = mul(v.vertex, unity_WorldToObject); 49 // 将纹理坐标赋值给v2f.uv并赋值面板贴图的旋转缩放 50 f.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw; 51 52 return f; 53 } 54 55 float4 frag(v2f f) : SV_Target{ 56 57 fixed3 lightDir = normalize(WorldSpaceLightDir(f.worldVertex)); 58 59 // tex2D 根据贴图获取模型纹理坐标身上对应的像素点颜色值 60 fixed3 texColor = tex2D(_MainTex,f.uv.xy) * _Color.rgb; 61 62 // 为漫反射混合上每个像素点的纹理颜色 63 fixed3 diffuse = _LightColor0.rgb * texColor * max(dot(f.worldNormal, lightDir), 0); 64 65 return fixed4(diffuse,1); 66 } 67 68 ENDCG 69 } 70 } 71 72 Fallback "VertexLit" 73 }