当前位置: 移动技术网 > IT编程>开发语言>c# > unity shader实现较完整光照效果

unity shader实现较完整光照效果

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了unity shader实现光照效果的具体代码,供大家参考,具体内容如下

效果图:

shader被附给了球。

灯光需要在属性面板开启阴影。

// upgrade note: replaced 'mul(unity_matrix_mvp,*)' with 'unityobjecttoclippos(*)'

shader "unlit/lightfull"
{
 properties
 {
 _maintex ("texture", 2d) = "white" {}
 }
 subshader
 {
 tags { "rendertype"="opaque" }
 lod 100

 pass
 {
 tags{"lightmode" = "forwardbase"}
 cgprogram
 #pragma vertex vert
 #pragma fragment frag
 // make fog work
 #pragma multi_compile_fwdbase
 
 #include "unitycg.cginc"
 #include "lighting.cginc"
 #include "autolight.cginc"
 struct appdata
 {
 float4 vertex : position;
 float2 uv : texcoord0;
 float3 normal : normal;
 };

 struct v2f
 {
 float2 uv : texcoord0;
 float4 pos : position;
 float4 pos_world : texcoord1;
 float3 normal:texcoord2;
 shadow_coords(3)
 };

 sampler2d _maintex;
 float4 _maintex_st;
 
 v2f vert (appdata v)
 {
 v2f o;
 o.pos_world = mul(unity_matrix_m, v.vertex);
 o.normal = v.normal;
 o.pos = unityobjecttoclippos(v.vertex);
 o.uv = transform_tex(v.uv, _maintex);
 transfer_shadow(o);
 return o;
 }
 
 fixed4 frag (v2f i) : sv_target
 {
 // sample the texture
 fixed4 col = tex2d(_maintex, i.uv);
 float4 lightcolor = _lightcolor0;
 float3 lightdir = worldspacelightdir(i.pos_world);
 unity_light_attenuation(atten, i, i.pos_world.xyz);
 return col * lightcolor * saturate(dot(lightdir, i.normal)) * atten;
 }
 endcg
 }
 pass
 {
 tags{"lightmode" = "forwardadd"}
 blend one one
 cgprogram
 #pragma vertex vert
 #pragma fragment frag
 #pragma multi_compile_fwdadd_fullshadows
 
 #include "unitycg.cginc"
 #include "lighting.cginc"
 #include "autolight.cginc"
 struct v2f
 {
 float4 pos : position;
 float4 vertex : texcoord0;
 float3 normal : normal;
 shadow_coords(2)
 };

 v2f vert(appdata_full data)
 {
 v2f v;
 v.pos = unityobjecttoclippos(data.vertex);
 v.vertex = mul(unity_matrix_m, data.vertex);
 v.normal = data.normal;
 transfer_shadow(v);
 return v;
 }

 float4 frag(v2f v) :sv_target
 {
 float3 lightcolor = _lightcolor0;
#ifdef using_directional_light
 float3 lightdir = _worldspacelightpos0;
#else
 float3 lightdir = _worldspacelightpos0 - v.vertex;
#endif
 unity_light_attenuation(atten, v, v.vertex.xyz);
 float3 color = lightcolor * saturate(dot(lightdir, v.normal) * atten);
 return float4(color, 1);
 }
 endcg
 }
 }
 fallback "specular"
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网