using
UnityEngine
;
using
System
.
Collections
;
[
ExecuteInEditMode
]
public
class
Mirror
:
MonoBehaviour
{
//
是否需要像素光
public
bool
m_DisablePixelLights
=
true
;
//
纹理大小
public
int
m_TextureSize
=
256
;
//
距离mirror表面距离偏移量
public
float
m_ClipPlaneOffset
=
0.07f
;
//
是否反射
public
bool
m_IsFlatMirror
=
true
;
//
cullMask层级
public
LayerMask
m_ReflectLayers
= –
1
;
//
camera哈希表
private
Hashtable
m_ReflectionCameras
=
new
Hashtable
();
//
反射纹理层
private
RenderTexture
m_ReflectionTexture
=
null
;
private
int
m_OldReflectionTextureSize
=
0
;
//
保证单次渲染
private
static
bool
s_InsideRendering
=
false
;
public
void
OnWillRenderObject
()
{
if
( !
enabled
|| !
renderer
|| !
renderer
.
sharedMaterial
|| !
renderer
.
enabled
)
return
;
//
当前用于渲染的相机
Camera
cam
=
Camera
.
current
;
if
( !
cam
)
return
;
if
(
s_InsideRendering
)
return
;
s_InsideRendering
=
true
;
Camera
reflectionCamera
;
//
camera数组中是否有currentCamera
,
没有的话根据currentCamera的ID创建一个赋给reflectionCamera,
//
并将reflectionCamera添加进camera数组中
CreateMirrorObjects
(
cam
,
out
reflectionCamera
);
Vector3
pos
=
transform
.
position
;
Vector3
normal
;
//
需要反射,法线沿表面向上
if
(
m_IsFlatMirror
){
normal
=
transform
.
up
;
}
//
不需要反射,法线沿表面向下
else
{
normal
=
transform
.
position
–
cam
.
transform
.
position
;
normal
.
Normalize
();
}
int
oldPixelLightCount
=
QualitySettings
.
pixelLightCount
;
if
(
m_DisablePixelLights
)
QualitySettings
.
pixelLightCount
=
0
;
//
使reflectionCamera配置跟camera一样
UpdateCameraModes
(
cam
,
reflectionCamera
);
float
d
= –
Vector3
.
Dot
(
normal
,
pos
) –
m_ClipPlaneOffset
;
Vector4
reflectionPlane
=
new
Vector4
(
normal
.
x
,
normal
.
y
,
normal
.
z