说明:创建两个代码文件

C#文件复制上MirrorReflection.CS带中文注释

创建Shader文件复制上MirrorReflection.Shader带中文注释

C#代码挂在unity平面片上,

建个材质球选择属性FX/Mirror,创建的Shader文件增加这个属性。

把材质赋予给平面片上,平面片就变成镜面反射了。

然后你在面片旁边加物体挪动,面片里面就会像一面镜子一样

面片背面是隐藏看不见的。

MirrorReflection.CS


代码

using UnityEngine;
using System.Collections;

// 这实际上是来自标准资产的水脚本,
// 只是用折射物去除。

[ExecuteInEditMode] // 即使不在播放模式,也可以进行镜像实时更新
public class MirrorReflection : MonoBehaviour
{
    public bool m_DisablePixelLights = true;
    public int m_TextureSize = 256;
    public float m_ClipPlaneOffset = 0.07f;
    
    public LayerMask m_ReflectLayers = -1;
        
    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 || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled )
            return;
            
        Camera cam = Camera.current;
        if( !cam )
            return;
    
        // 从递归反射中得到保护      
        if( s_InsideRendering )
            return;
        s_InsideRendering = true;
        
        Camera reflectionCamera;
        CreateMirrorObjects( cam, out reflectionCamera );
        
        // 找出反射平面:世界空间中的位置和法线
        Vector3 pos = transform.position;
        Vector3 normal = transform.up;
        
        // 可选禁用反射像素灯
        int oldPixelLightCount = QualitySettings.pixelLightCount;
        if( m_DisablePixelLights )
            QualitySettings.pixelLightCount = 0;
        
        UpdateCameraModes( cam, reflectionCamera );
        
        // 渲染反射
        // 反射面反射照相机
        float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
        Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
    
        Matrix4x4 reflection = Matrix4x4.zero;
        CalculateReflectionMatrix (ref reflection, reflectionPlane);
        Vector3 oldpos = cam.transform.position;
        Vector3 newpos = reflection.MultiplyPoint( oldpos );
        reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
    
        // 设置斜投影矩阵,使近平面成为我们的反射。
        // 平面。这样我们就可以把所有的东西都放在下面/上面。
        Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
        Matrix4x4 projection = cam.projectionMatrix;
        CalculateObliqueMatrix (ref projection, clipPlane);
        reflectionCamera.projectionMatrix = projection;
        
        reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // 永不渲染水层
        reflectionCamera.targetTexture = m_ReflectionTexture;
        GL.SetRevertBackfacing (true);
        reflectionCamera.transform.position = newpos;
        Vector3 euler = cam.transform.eulerAngles;
        reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
        reflectionCamera.Render();
        reflectionCamera.transform.position = oldpos;
        GL.SetRevertBackfacing (false);
        Material[] materials = GetComponent<Renderer>().sharedMaterials;
        foreach( Material mat in materials ) {
            if( mat.HasProperty("_ReflectionTex") )
                mat.SetTexture( "_ReflectionTex", m_ReflectionTexture );
        }
        
        // 设置矩阵变换的UV从对象空间到屏幕材质
        // 空间。我们只想在屏幕上投射反射纹理
        Matrix4x4 scaleOffset = Matrix4x4.TRS(
            new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) );
        Vector3 scale = transform.lossyScale;
        Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) );
        mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
        foreach( Material mat in materials ) {
            mat.SetMatrix( "_ProjMatrix", mtx );
        }
        
        // 恢复像素光计数
        if( m_DisablePixelLights )
            QualitySettings.pixelLightCount = oldPixelLightCount;
        
        s_InsideRendering = false;
    }
    
    
    // 清理我们可能创建的所有对象
    void OnDisable()
    {
        if( m_ReflectionTexture ) {
            DestroyImmediate( m_ReflectionTexture );
            m_ReflectionTexture = null;
        }
        foreach( DictionaryEntry kvp in m_ReflectionCameras )
            DestroyImmediate( ((Camera)kvp.Value).gameObject );
        m_ReflectionCameras.Clear();
    }
    
    
    private void UpdateCameraModes( Camera src, Camera dest )
    {
        if( dest == null )
            return;
        // 设置相机以与当前相机相同的方式清除
        dest.clearFlags = src.clearFlags;
        dest.backgroundColor = src.backgroundColor;        
        if( src.clearFlags == CameraClearFlags.Skybox )
        {
            Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
            Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
            if( !sky || !sky.material )
            {
                mysky.enabled = false;
            }
            else
            {
                mysky.enabled = true;
                mysky.material = sky.material;
            }
        }
        // 更新其他值以匹配当前相机。
        // 即使我们提供定制的相机和投影矩阵
        // 一些价值被用在其他地方(例如Skybox利用远平面)
        dest.farClipPlane = src.farClipPlane;
        dest.nearClipPlane = src.nearClipPlane;
        dest.orthographic = src.orthographic;
        dest.fieldOfView = src.fieldOfView;
        dest.aspect = src.aspect;
        dest.orthographicSize = src.orthographicSize;
    }
    
    // 按需创建任何我们需要的对象
    private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera )
    {
        reflectionCamera = null;
        
        // 反射的渲染纹理
        if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
        {
            if( m_ReflectionTexture )
                DestroyImmediate( m_ReflectionTexture );
            m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
            m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
            m_ReflectionTexture.isPowerOfTwo = true;
            m_ReflectionTexture.hideFlags = HideFlags.DontSave;
            m_OldReflectionTextureSize = m_TextureSize;
        }
        
        // 相机反射
        reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
        if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
        {
            GameObject go = new GameObject( "Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
            reflectionCamera = go.GetComponent<Camera>();
            reflectionCamera.enabled = false;
            reflectionCamera.transform.position = transform.position;
            reflectionCamera.transform.rotation = transform.rotation;
            reflectionCamera.gameObject.AddComponent<FlareLayer>();
            go.hideFlags = HideFlags.HideAndDontSave;
            m_ReflectionCameras[currentCamera] = reflectionCamera;
        }        
    }
    
    // 扩展符号:返回-基于符号的1, 0或1
    private static float sgn(float a)
    {
        if (a > 0.0f) return 1.0f;
        if (a < 0.0f) return -1.0f;
        return 0.0f;
    }
    
    //给定平面的位置/法线,在相机空间中计算平面。
    private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
    {
        Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
        Matrix4x4 m = cam.worldToCameraMatrix;
        Vector3 cpos = m.MultiplyPoint( offsetPos );
        Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
        return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
    }
    
    // 调整给定的投影矩阵,使近平面为给定的裁剪平面。
    // 剪辑平面是在相机空间中给出的。参见游戏编程宝石5。
    private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
    {
        Vector4 q = projection.inverse * new Vector4(
            sgn(clipPlane.x),
            sgn(clipPlane.y),
            1.0f,
            1.0f
        );
        Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
        // 第三行=剪辑平面-第四行
        projection[2] = c.x - projection[3];
        projection[6] = c.y - projection[7];
        projection[10] = c.z - projection[11];
        projection[14] = c.w - projection[15];
    }

	// 计算给定平面周围的反射矩阵。
	private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
	{
		reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
		reflectionMat.m01 = (   - 2F*plane[0]*plane[1]);
		reflectionMat.m02 = (   - 2F*plane[0]*plane[2]);
		reflectionMat.m03 = (   - 2F*plane[3]*plane[0]);

		reflectionMat.m10 = (   - 2F*plane[1]*plane[0]);
		reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
		reflectionMat.m12 = (   - 2F*plane[1]*plane[2]);
		reflectionMat.m13 = (   - 2F*plane[3]*plane[1]);

		reflectionMat.m20 = (   - 2F*plane[2]*plane[0]);
		reflectionMat.m21 = (   - 2F*plane[2]*plane[1]);
		reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
		reflectionMat.m23 = (   - 2F*plane[3]*plane[2]);

		reflectionMat.m30 = 0F;
		reflectionMat.m31 = 0F;
		reflectionMat.m32 = 0F;
		reflectionMat.m33 = 1F;
	}
}

shader代码

Shader "FX/Mirror" { 
Properties {
    _MainTex ("Base (RGB)", 2D) = "white" {}
    _ReflectionTex ("Reflection", 2D) = "white" { TexGen ObjectLinear }
}

// 两张纹理卡片:完整的东西
Subshader { 
    Pass {
        SetTexture[_MainTex] { combine texture }
        SetTexture[_ReflectionTex] { matrix [_ProjMatrix] combine texture * previous }
    }
}

// 后退:只是主纹理
Subshader {
    Pass {
        SetTexture [_MainTex] { combine texture }
    }
}

}