Unity之计算环境反射WorldRefl

在游戏中,有时需要反射环境,如果用SurfaceShader会比较简单,但是surfaceShader的性能比较差,所以经常需要自己写Vertex/Fragment Shader来处理。

首先通过一个Editor脚本来创建Cubemap( 可以在我博客主面的git地址里找)。

在顶点着色器里

v2f vert (appdata_full v)
{
	v2f o;
	
	o.pos	= mul(UNITY_MATRIX_MVP, v.vertex);
	o.uv		= v.texcoord;
	
	float3 worldNormal = mul((float3x3)_Object2World, v.normal);
	o.refl = reflect(-WorldSpaceViewDir(v.vertex), worldNormal);
	o.refl.x = -o.refl.x;
	
	#ifndef LIGHTMAP_OFF
	o.lmap = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;
	#endif
	
	
	return o;
}


在片断着色器里

fixed4 frag (v2f i) : COLOR
{
	fixed4 c 	= tex2D (_MainTex, i.uv.xy);
	
	#ifndef LIGHTMAP_OFF
	c.xyz *= DecodeLightmap (tex2D(unity_Lightmap, i.lmap));
	#endif
	
	c.xyz += texCUBE(_EnvTex,i.refl) * c.a;
	
	return c;
}


你可能感兴趣的:(Unity)