先上图:
看着不太对是因为skybox的问题,skybox没底部图片,所以用了top图片。
下面是代码:
Shader "Custom/ShaderExample2"
{
Properties
{
_Cube("Reflection Map", Cube) = "" {}
}
SubShader
{
Pass
{
GLSLPROGRAM
#extension GL_NV_shadow_samplers_cube : enable
uniform mat4 _Object2World;
uniform mat4 _World2Object;
uniform vec3 _WorldSpaceCameraPos; //view位置
uniform samplerCube _Cube;
#ifdef VERTEX
//顶点着色器
out vec3 normalDirection;
out vec3 viewDirection;
void main()
{
mat4 modelMatrix = _Object2World;
mat4 modelMatrixInverse = _World2Object;
normalDirection = normalize(vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));
viewDirection = vec3(modelMatrix * gl_Vertex - vec4(_WorldSpaceCameraPos, 1.0));
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
#endif
#ifdef FRAGMENT
//片元着色器
in vec3 normalDirection;
in vec3 viewDirection;
void main()
{
//根据normal和入射光计算反射光的公式:refDir = 2 * (dot(n, l)) * n - l
//此处viewDirection必须指向view,所以添加了一个负号
//vec3 reflectedDir = 2 * dot(normalDirection, (-viewDirection)) * normalDirection - (-viewDirection);
vec3 reflectedDir = reflect(viewDirection, normalize(normalDirection));
//上面的两行代码效果是一样的,,都是计算反射光,只不过opengl提供了reflect反射函数,可以直接用,注意viewDirection
gl_FragColor = textureCube(_Cube, reflectedDir);
}
#endif
ENDGLSL
}
}
}