赞
踩
做项目的时候要用到镜子,折腾了一下午,发现做镜子还是蛮快的,总结了一下网上的教程,大致有这么几种做法:
1、使用反射探针(Reflection Probe)
2、使用Render Texture
3、使用Shader着色器,我发现这种方法步骤比较少,而且重复使用起来也方便
下面就介绍一下这个方法,以及期间我踩过的坑;官方的教程在这里:MirrorReflection4
(我之所以说比较简单,是因为Shader方法可以用网上现成的代码,基本不用改
话不多说进入正题:
首先利用Shader做镜子,需要两段代码,一个是.shader着色器代码,另一个是C#脚本代码
着色器代码如下:
- Shader "FX/MirrorReflection"
- {
- Properties
- {
- _MainTex ("Base (RGB)", 2D) = "white" {}
- [HideInInspector] _ReflectionTex ("", 2D) = "white" {}
- }
- SubShader
- {
- Tags { "RenderType"="Opaque" }
- LOD 100
-
- Pass {
- CGPROGRAM
- #pragma vertex vert
- #pragma fragment frag
- #include "UnityCG.cginc"
- struct v2f
- {
- float2 uv : TEXCOORD0;
- float4 refl : TEXCOORD1;
- float4 pos : SV_POSITION;
- };
- float4 _MainTex_ST;
- v2f vert(float4 pos : POSITION, float2 uv : TEXCOORD0)
- {
- v2f o;
- o.pos = mul (UNITY_MATRIX_MVP, pos);
- o.uv = TRANSFORM_TEX(uv, _MainTex);
- o.refl = ComputeScreenPos (o.pos);
- return o;
- }
- sampler2D _MainTex;
- sampler2D _ReflectionTex;
- fixed4 frag(v2f i) : SV_Target
- {
- fixed4 tex = tex2D(_MainTex, i.uv);
- fixed4 refl = tex2Dproj(_ReflectionTex, UNITY_PROJ_COORD(i.refl));
- return tex * refl;
- }
- ENDCG
- }
- }
- }
C#脚本代码如下:
- using UnityEngine;
- using System.Collections;
-
- // This is in fact just the Water script from Pro Standard Assets,
- // just with refraction stuff removed.
-
- [ExecuteInEditMode] // Make mirror live-update even when not in play mode
- 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(); // Camera -> Camera table
-
- private RenderTexture m_ReflectionTexture = null;
- private int m_OldReflectionTextureSize = 0;
-
- private static bool s_InsideRendering = false;
-
- // This is called when it's known that the object will be rendered by some
- // camera. We render reflections and do other updates here.
- // Because the script executes in edit mode, reflections for the scene view
- // camera will just work!
- public void OnWillRenderObject()
- {
- var rend = GetComponent<Renderer>();
- if (!enabled || !rend || !rend.sharedMaterial || !rend.enabled)
- return;
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。