Unity3d中获取手机中的摄像头

来源:互联网 发布:手机相片加密软件 编辑:程序博客网 时间:2024/05/27 19:28
首先,我们先要设置好用于展示摄像头内容的材质,在这里有一个shader文件,用这个shader创建一个材质
Shader "Unlit/CameraShader"{Properties{_MainTex ("Texture", 2D) = "white" {}        _ColorChangeY("ColorChangeY",Range(0,1))=0}SubShader{Tags {"RenderType"="Transparent" "Queue"="Transparent" }LOD 200Cull OffLighting OffPass{CGPROGRAM#pragma vertex vert            #pragma fragment frag                        #include "UnityCG.cginc"sampler2D _MainTex;            float _ColorChangeY;  struct appdata            {                float4 vertex : POSITION;                float2 uv : TEXCOORD0;            };            struct v2f            {                float2 uv : TEXCOORD0;                float4 vertex : SV_POSITION;            };v2f vert (appdata v){v2f o;o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);o.uv = v.uv;return o;}fixed4 frag (v2f i) : SV_Target{         fixed4 mainCol= tex2D(_MainTex, i.uv);if(i.uv.x<_ColorChangeY){float r=mainCol.g;mainCol.g=(1-mainCol.b)*0.5f;    mainCol.b=(1-mainCol.r)*0.5f;    mainCol.r=(1-r)*0.5;}return mainCol ;}ENDCG}}}
然后设置一个panle,用来接收摄像机传回来的内容,他的材质为上面的shader制成的材质
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;public class OpenCamera : MonoBehaviour{    //摄像机;    WebCamTexture WCT;    /// <summary>    /// 单例;    /// </summary>    public static OpenCamera Instance;    //控制的贴图材质;    public Material Mat;    /// <summary>    /// 控制的平面;    /// </summary>    public Transform CameraPlane;            void Start ()    {        CameraPlane.transform.localEulerAngles = new Vector3(-180, 90, -90);        //苹果系统下旋转一下贴图平面;#if UNITY_IOS || UNITY_IPHONE        //设置平板的旋转;        CameraPlane.transform.localEulerAngles = new Vector3(-180, 270, -90);#endif        //开启摄像机;        CameraPlane.gameObject.SetActive(true);        RestartCamera();}        /// <summary>    /// 使用摄像机的方法;    /// </summary>    /// <returns></returns>    IEnumerator CallCamera()    {        //调整宽高;        //AndroidManager.getInstance().GetMessageFromIOSorAndroid("2006#" + 1800 + "*" + 900);        Debug.Log("开始开摄像头");        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);        if (Application.HasUserAuthorization(UserAuthorization.WebCam))        {            if (WCT != null) WCT.Stop();            //获取摄像机;            WebCamDevice[] cameraDivices = WebCamTexture.devices;            if (cameraDivices.Length > 0)            {                //第一个摄像机;                string deviceName = cameraDivices[0].name;                //制作摄像机背景贴图;                WCT = new WebCamTexture(deviceName, Width, Heigh, 30);                                //WCT = new WebCamTexture(deviceName);                //贴图应用到面板;                Mat.mainTexture = WCT;                WCT.Play();            }        }


 
原创粉丝点击