当前位置:   article > 正文

Unity中用Shader实现镜子效果_mirror shaders

mirror shaders

做项目的时候要用到镜子,折腾了一下午,发现做镜子还是蛮快的,总结了一下网上的教程,大致有这么几种做法:

1、使用反射探针(Reflection Probe)

2、使用Render Texture

3、使用Shader着色器,我发现这种方法步骤比较少,而且重复使用起来也方便

下面就介绍一下这个方法,以及期间我踩过的坑;官方的教程在这里:MirrorReflection4

(我之所以说比较简单,是因为Shader方法可以用网上现成的代码,基本不用改

话不多说进入正题:

首先利用Shader做镜子,需要两段代码,一个是.shader着色器代码,另一个是C#脚本代码

着色器代码如下:

Mirror.shader

  1. Shader "FX/MirrorReflection"
  2. {
  3. Properties
  4. {
  5. _MainTex ("Base (RGB)", 2D) = "white" {}
  6. [HideInInspector] _ReflectionTex ("", 2D) = "white" {}
  7. }
  8. SubShader
  9. {
  10. Tags { "RenderType"="Opaque" }
  11. LOD 100
  12. Pass {
  13. CGPROGRAM
  14. #pragma vertex vert
  15. #pragma fragment frag
  16. #include "UnityCG.cginc"
  17. struct v2f
  18. {
  19. float2 uv : TEXCOORD0;
  20. float4 refl : TEXCOORD1;
  21. float4 pos : SV_POSITION;
  22. };
  23. float4 _MainTex_ST;
  24. v2f vert(float4 pos : POSITION, float2 uv : TEXCOORD0)
  25. {
  26. v2f o;
  27. o.pos = mul (UNITY_MATRIX_MVP, pos);
  28. o.uv = TRANSFORM_TEX(uv, _MainTex);
  29. o.refl = ComputeScreenPos (o.pos);
  30. return o;
  31. }
  32. sampler2D _MainTex;
  33. sampler2D _ReflectionTex;
  34. fixed4 frag(v2f i) : SV_Target
  35. {
  36. fixed4 tex = tex2D(_MainTex, i.uv);
  37. fixed4 refl = tex2Dproj(_ReflectionTex, UNITY_PROJ_COORD(i.refl));
  38. return tex * refl;
  39. }
  40. ENDCG
  41. }
  42. }
  43. }

C#脚本代码如下:

MirrorReflection.cs

  1. using UnityEngine;
  2. using System.Collections;
  3. // This is in fact just the Water script from Pro Standard Assets,
  4. // just with refraction stuff removed.
  5. [ExecuteInEditMode] // Make mirror live-update even when not in play mode
  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(); // Camera -> Camera table
  13. private RenderTexture m_ReflectionTexture = null;
  14. private int m_OldReflectionTextureSize = 0;
  15. private static bool s_InsideRendering = false;
  16. // This is called when it's known that the object will be rendered by some
  17. // camera. We render reflections and do other updates here.
  18. // Because the script executes in edit mode, reflections for the scene view
  19. // camera will just work!
  20. public void OnWillRenderObject()
  21. {
  22. var rend = GetComponent<Renderer>();
  23. if (!enabled || !rend || !rend.sharedMaterial || !rend.enabled)
  24. return;
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/108417
推荐阅读
相关标签
  

闽ICP备14008679号