Unity ImageEfffect 摄像头画面镜像处理

来源:互联网 发布:校园网络组建方案设计 编辑:程序博客网 时间:2024/05/18 01:00

让摄像头的画面发生镜像变换。





直接上代码。

 

public bool NeedRevert = false;public Shader invertShader = Shader.Find ("Custom/FrontCameraInvertImage");static Material m_Material = null;protected Material material{get{if (m_Material == null){m_Material = new Material(invertShader);m_Material.hideFlags = HideFlags.DontSave;}return m_Material;}}protected void OnDisable(){if (m_Material){DestroyImmediate(m_Material);}}// Called by the camera to apply the image effectvoid OnRenderImage(RenderTexture source, RenderTexture destination){if (NeedRevert && isInit) {if (Screen.orientation == ScreenOrientation.Portrait || Screen.orientation == ScreenOrientation.PortraitUpsideDown) {material.SetFloat ("_AxisX",0);}else{material.SetFloat ("_AxisX",1);}Graphics.Blit (source, destination, material);}else Graphics.Blit(source, destination);}

如果是竖屏X轴镜像,material.SetFloat ("_AxisX",0);

如果是竖屏Y轴镜像,material.SetFloat ("_AxisX",1);

如果是横屏X轴镜像,material.SetFloat ("_AxisX",1);

如果是横屏Y轴镜像,material.SetFloat ("_AxisX",0);


最后是shader的代码

Shader "Custom/FrontCameraInvertImage" {Properties{_MainTex("Base (RGB)", 2D) = "" {}_AxisX("x or y", Range(0,1)) = 0 //0 for x; 1 for y}// Shader code pasted into all further CGPROGRAM blocksCGINCLUDE#include "UnityCG.cginc"struct v2f {float4 pos : SV_POSITION;float2 uv : TEXCOORD0;};sampler2D _MainTex;half4 _MainTex_ST;float _AxisX;v2f vert(appdata_img v){v2f o;o.pos = UnityObjectToClipPos(v.vertex);o.uv = v.texcoord.xy;return o;}half4 frag(v2f i) : SV_Target{if(_AxisX == 0)i.uv.x = 1 - i.uv.x;else i.uv.y = 1 - i.uv.y;half4 color = tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv, _MainTex_ST));return color;}ENDCGSubshader {Pass{ZTest Always Cull Off ZWrite OffCGPROGRAM#pragma vertex vert#pragma fragment fragENDCG}}Fallback off} // shader

以上效果只会对摄像头起作用。


最后提出一个问题:Input点击事件也发生了镜像,可以用Screen.width-Input.mousePosition.x 来解决。

但是,如果是UI的事件,就要通过修改系统的事件

原创粉丝点击