Shader "Custom/ReflectionShader"
{
Properties
{
_Cubemap("Cubemap", Cube) = "" {}
_ReflectionAmount("Reflection Amount", Range(0, 1)) = 0.5
_ReflectColor("Reflection Color",Color) = (1,1,1,1) //控制反射颜色
}
SubShader
{
Pass
{
Tags
{
"LightMode" = "ForwardBase"
}
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fwdbase
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"
samplerCUBE _Cubemap;
float _ReflectionAmount;
fixed4 _ReflectColor;
struct appdata
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float3 normal : NORMAl;
};
struct v2f
{
float4 pos : SV_POSITION;
fixed4 color : COLOR;
float3 worldNormal : TEXCOORD0;
float3 worldPos : TEXCOORD1;
SHADOW_COORDS(2)
};
v2f vert(appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.color = v.color;
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
TRANSFER_SHADOW(o);
return o;
}
fixed4 frag(v2f i) : SV_TARGET
{
fixed3 albedo = i.color.rgb;
fixed3 ambient = albedo * UNITY_LIGHTMODEL_AMBIENT.rgb ;
float3 worldLight = UnityWorldSpaceLightDir(i.worldPos);
fixed3 diffuse = albedo * _LightColor0.rgb * max(0, dot(worldLight, i.worldNormal));
float3 worldView = UnityWorldSpaceViewDir(i.worldPos);
//物体反射到摄像机中的光线,可以由光路可逆的原则来反向求得 也就是说我们可以计算视角方向关于顶点发现的反射方向来球的入射光线的方向
float3 refDir = reflect(-worldView, i.worldNormal);
fixed3 refCol = texCUBE(_Cubemap, refDir) * _ReflectColor.rgb;//worldRefl 仅作为方向传给texCUBE函数 所以不需要归一化
UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
fixed3 col = ambient + lerp(diffuse, refCol, _ReflectionAmount) * atten;
return fixed4(col, 1);
}
ENDCG
}
}
Fallback "VertexLit"
}
shader学习之路——反射
最新推荐文章于 2023-11-21 11:52:33 发布