当前位置:   article > 正文

Unity中镜子面片_cameraspaceplane

cameraspaceplane
说明:创建两个代码文件
C#文件复制上MirrorReflection.CS带中文注释
创建Shader文件复制上MirrorReflection.Shader带中文注释
C#代码挂在unity平面片上,
建个材质球选择属性FX/Mirror,创建的Shader文件增加这个属性。
把材质赋予给平面片上,平面片就变成镜面反射了。
然后你在面片旁边加物体挪动,面片里面就会像一面镜子一样

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

MirrorReflection.CS


代码

  1. using UnityEngine;
  2. using System.Collections;
  3. // 这实际上是来自标准资产的水脚本,
  4. // 只是用折射物去除。
  5. [ExecuteInEditMode] // 即使不在播放模式,也可以进行镜像实时更新
  6. public class MirrorReflection : MonoBehaviour
  7. {
  8. public bool m_DisablePixelLights = true;
  9. public int m_TextureSize = 256;
  10. public float m_ClipPlaneOffset = 0.07f;
  11. public LayerMask m_ReflectLayers = -1;
  12. private Hashtable m_ReflectionCameras = new Hashtable(); // 摄像机>摄像机表
  13. private RenderTexture m_ReflectionTexture = null;
  14. private int m_OldReflectionTextureSize = 0;
  15. private static bool s_InsideRendering = false;
  16. // 当知道对象将由一些人呈现时,这就被调用了。
  17. // 相机。我们在这里渲染倒影并做其他的更新
  18. // 因为脚本是在编辑模式下执行的,所以对场景视图进行了反射。
  19. // 照相机就可以工作了!!
  20. public void OnWillRenderObject()
  21. {
  22. if( !enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled )
  23. return;
  24. Camera cam = Camera.current;
  25. if( !cam )
  26. return;
  27. // 从递归反射中得到保护
  28. if( s_InsideRendering )
  29. return;
  30. s_InsideRendering = true;
  31. Camera reflectionCamera;
  32. CreateMirrorObjects( cam, out reflectionCamera );
  33. // 找出反射平面:世界空间中的位置和法线
  34. Vector3 pos = transform.position;
  35. Vector3 normal = transform.up;
  36. // 可选禁用反射像素灯
  37. int oldPixelLightCount = QualitySettings.pixelLightCount;
  38. if( m_DisablePixelLights )
  39. QualitySettings.pixelLightCount = 0;
  40. UpdateCameraModes( cam, reflectionCamera );
  41. // 渲染反射
  42. // 反射面反射照相机
  43. float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
  44. Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
  45. Matrix4x4 reflection = Matrix4x4.zero;
  46. CalculateReflectionMatrix (ref reflection, reflectionPlane);
  47. Vector3 oldpos = cam.transform.position;
  48. Vector3 newpos = reflection.MultiplyPoint( oldpos );
  49. reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
  50. // 设置斜投影矩阵,使近平面成为我们的反射。
  51. // 平面。这样我们就可以把所有的东西都放在下面/上面。
  52. Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
  53. Matrix4x4 projection = cam.projectionMatrix;
  54. CalculateObliqueMatrix (ref projection, clipPlane);
  55. reflectionCamera.projectionMatrix = projection;
  56. reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // 永不渲染水层
  57. reflectionCamera.targetTexture = m_ReflectionTexture;
  58. GL.SetRevertBackfacing (true);
  59. reflectionCamera.transform.position = newpos;
  60. Vector3 euler = cam.transform.eulerAngles;
  61. reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
  62. reflectionCamera.Render();
  63. reflectionCamera.transform.position = oldpos;
  64. GL.SetRevertBackfacing (false);
  65. Material[] materials = GetComponent<Renderer>().sharedMaterials;
  66. foreach( Material mat in materials ) {
  67. if( mat.HasProperty("_ReflectionTex") )
  68. mat.SetTexture( "_ReflectionTex", m_ReflectionTexture );
  69. }
  70. // 设置矩阵变换的UV从对象空间到屏幕材质
  71. // 空间。我们只想在屏幕上投射反射纹理
  72. Matrix4x4 scaleOffset = Matrix4x4.TRS(
  73. new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) );
  74. Vector3 scale = transform.lossyScale;
  75. Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) );
  76. mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
  77. foreach( Material mat in materials ) {
  78. mat.SetMatrix( "_ProjMatrix", mtx );
  79. }
  80. // 恢复像素光计数
  81. if( m_DisablePixelLights )
  82. QualitySettings.pixelLightCount = oldPixelLightCount;
  83. s_InsideRendering = false;
  84. }
  85. // 清理我们可能创建的所有对象
  86. void OnDisable()
  87. {
  88. if( m_ReflectionTexture ) {
  89. DestroyImmediate( m_ReflectionTexture );
  90. m_ReflectionTexture = null;
  91. }
  92. foreach( DictionaryEntry kvp in m_ReflectionCameras )
  93. DestroyImmediate( ((Camera)kvp.Value).gameObject );
  94. m_ReflectionCameras.Clear();
  95. }
  96. private void UpdateCameraModes( Camera src, Camera dest )
  97. {
  98. if( dest == null )
  99. return;
  100. // 设置相机以与当前相机相同的方式清除
  101. dest.clearFlags = src.clearFlags;
  102. dest.backgroundColor = src.backgroundColor;
  103. if( src.clearFlags == CameraClearFlags.Skybox )
  104. {
  105. Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
  106. Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
  107. if( !sky || !sky.material )
  108. {
  109. mysky.enabled = false;
  110. }
  111. else
  112. {
  113. mysky.enabled = true;
  114. mysky.material = sky.material;
  115. }
  116. }
  117. // 更新其他值以匹配当前相机。
  118. // 即使我们提供定制的相机和投影矩阵
  119. // 一些价值被用在其他地方(例如Skybox利用远平面)
  120. dest.farClipPlane = src.farClipPlane;
  121. dest.nearClipPlane = src.nearClipPlane;
  122. dest.orthographic = src.orthographic;
  123. dest.fieldOfView = src.fieldOfView;
  124. dest.aspect = src.aspect;
  125. dest.orthographicSize = src.orthographicSize;
  126. }
  127. // 按需创建任何我们需要的对象
  128. private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera )
  129. {
  130. reflectionCamera = null;
  131. // 反射的渲染纹理
  132. if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
  133. {
  134. if( m_ReflectionTexture )
  135. DestroyImmediate( m_ReflectionTexture );
  136. m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
  137. m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
  138. m_ReflectionTexture.isPowerOfTwo = true;
  139. m_ReflectionTexture.hideFlags = HideFlags.DontSave;
  140. m_OldReflectionTextureSize = m_TextureSize;
  141. }
  142. // 相机反射
  143. reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
  144. if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
  145. {
  146. GameObject go = new GameObject( "Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
  147. reflectionCamera = go.GetComponent<Camera>();
  148. reflectionCamera.enabled = false;
  149. reflectionCamera.transform.position = transform.position;
  150. reflectionCamera.transform.rotation = transform.rotation;
  151. reflectionCamera.gameObject.AddComponent<FlareLayer>();
  152. go.hideFlags = HideFlags.HideAndDontSave;
  153. m_ReflectionCameras[currentCamera] = reflectionCamera;
  154. }
  155. }
  156. // 扩展符号:返回-基于符号的1, 0或1
  157. private static float sgn(float a)
  158. {
  159. if (a > 0.0f) return 1.0f;
  160. if (a < 0.0f) return -1.0f;
  161. return 0.0f;
  162. }
  163. //给定平面的位置/法线,在相机空间中计算平面。
  164. private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
  165. {
  166. Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
  167. Matrix4x4 m = cam.worldToCameraMatrix;
  168. Vector3 cpos = m.MultiplyPoint( offsetPos );
  169. Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
  170. return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
  171. }
  172. // 调整给定的投影矩阵,使近平面为给定的裁剪平面。
  173. // 剪辑平面是在相机空间中给出的。参见游戏编程宝石5。
  174. private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
  175. {
  176. Vector4 q = projection.inverse * new Vector4(
  177. sgn(clipPlane.x),
  178. sgn(clipPlane.y),
  179. 1.0f,
  180. 1.0f
  181. );
  182. Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
  183. // 第三行=剪辑平面-第四行
  184. projection[2] = c.x - projection[3];
  185. projection[6] = c.y - projection[7];
  186. projection[10] = c.z - projection[11];
  187. projection[14] = c.w - projection[15];
  188. }
  189. // 计算给定平面周围的反射矩阵。
  190. private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
  191. {
  192. reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
  193. reflectionMat.m01 = ( - 2F*plane[0]*plane[1]);
  194. reflectionMat.m02 = ( - 2F*plane[0]*plane[2]);
  195. reflectionMat.m03 = ( - 2F*plane[3]*plane[0]);
  196. reflectionMat.m10 = ( - 2F*plane[1]*plane[0]);
  197. reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
  198. reflectionMat.m12 = ( - 2F*plane[1]*plane[2]);
  199. reflectionMat.m13 = ( - 2F*plane[3]*plane[1]);
  200. reflectionMat.m20 = ( - 2F*plane[2]*plane[0]);
  201. reflectionMat.m21 = ( - 2F*plane[2]*plane[1]);
  202. reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
  203. reflectionMat.m23 = ( - 2F*plane[3]*plane[2]);
  204. reflectionMat.m30 = 0F;
  205. reflectionMat.m31 = 0F;
  206. reflectionMat.m32 = 0F;
  207. reflectionMat.m33 = 1F;
  208. }
  209. }

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 }
    }
}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/108367
推荐阅读
相关标签
  

闽ICP备14008679号