UnityShader学习-纹理shader

// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'

Shader "Custom/SingleTexture"
 {
	Properties
	 {
		_Color ("Color", Color) = (1,1,1,1)
		_MainTex ("Albedo (RGB)", 2D) = "white" {}
		_Glossiness ("Smoothness", Range(8.0,256)) = 20
		_Specular ("Specular", Color) = (1,1,1,1)
	}
	SubShader 
	{
		//_LightColor0只有定义了"LightMode" = "ForwardBase"才正确
		Tags { "RenderType"="Opaque" "LightMode" = "ForwardBase"}
		Pass 
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc" 
			#include "Lighting.cginc"

			fixed4 _Color;
			sampler2D _MainTex;
			float4 _MainTex_ST;
			float _Glossiness;
			fixed4 _Specular;

			struct a2v
			{
				float4 vertex:POSITION;  //顶点坐标
				float3 normal:NORMAL;	 //顶点法线
				float4 texcoord:TEXCOORD0; //第一组纹理坐标
			};

			struct v2f
			{
				float4 pos:SV_POSITION; //裁剪空间的位置,顶点着色器必做的操作,把顶点从模型空间转换到裁剪空间
				float4 worldPos:TEXCOORD0;//世界坐标,用于计算光照
				float3 worldNormal:TEXCOORD1;//世界法线,用于计算光照
				float2 uv:TEXCOORD2;//采样得到的UV值
			};

			v2f vert(a2v v)
			{
				v2f o;
				o.pos = UnityObjectToClipPos(v.vertex);	//模型坐标转到裁剪坐标
				o.worldPos = mul(unity_ObjectToWorld,v.vertex); //得到世界坐标
				o.worldNormal = UnityObjectToWorldNormal(v.normal);	//得到世界法线量
				o.uv = TRANSFORM_TEX(v.texcoord,_MainTex); //对顶点的纹理坐标转换得到最终的UV值
				return o;
			}

			fixed4 frag(v2f i):SV_Target
			{
				fixed3 worldNormal = normalize(i.worldNormal);//计算出归一化的世界法线
				fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));//归一化的从点到光源的方向
				fixed3 abedo = tex2D(_MainTex,i.uv).rgb * _Color.rgb;//本身的颜色
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;//环境光

				fixed3 halfLambert = dot(worldNormal,worldLightDir) * 0.5 + 0.5;//半兰伯特模型
				fixed3 diffuse = _LightColor0.rgb * abedo * halfLambert;//漫反射颜色
				fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));//从该点到相机的方向
				fixed3 halfDir = normalize(worldLightDir + viewDir);//Phong模型
				fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0,dot(worldNormal,halfDir)),_Glossiness);//高光反射
				return fixed4(ambient + diffuse + specular,1);//最终颜色
			}
			ENDCG
		}
	}
	FallBack "Specular"
}
 

一开始没有定义Tags { "RenderType"="Opaque" "LightMode" = "ForwardBase"} 导致效果不对一直不对,定义了才好了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值