使用unity3D開發同時打開手機先後攝像頭實例程序

         本文講的這個程序是很是基礎的。主要功能是同時打開手機先後攝像頭,而且顯示在屏幕上。在作這個實驗以前,須要先配置Unity3D的安卓開發環境,這須要下載JDK和安卓SDK,具體的步驟請參照網上的教程。本文假設你已經配置好了環境。css



        在Unity的場景中生成如圖所示的兩個平板,一大一小,做爲圖像的載體。須要有一個攝像機來拍攝這兩塊板子,用於呈現最終的畫面。我使用的是正交攝像機,這樣比較好調整位置。固然是用透視攝像機也是能夠的。而後將下面的ReadCamera.cs腳本綁定到MainCamera上。其中有幾個公有變量須要設置一下。Plane1Plane2分別綁定先後兩個板子。GuiSkin須要本身先生成一個,而後設置好相關參數,再綁定到GuiSkin上。markdown

        發佈一個APK文件,安裝到手機上,便可觀看到結果。ui



using UnityEngine;
using System.Collections;
public class ReadCamera : MonoBehaviour {
    public string deviceName1;
    WebCamTexture tex1;//接收返回的圖片數據 
    public string deviceName2;
    WebCamTexture tex2;//接收返回的圖片數據 
    public GameObject plane1;
    public GameObject plane2;
    bool turn = true;
    public GUISkin guiSkin;
	void Start () {
        StartCoroutine(test1());
        StartCoroutine(test2());    
	}
	
	// Update is called once per frame
	void Update () {
        plane1.GetComponent<Renderer>().material.mainTexture = turn?tex1:tex2;
        plane2.GetComponent<Renderer>().material.mainTexture = turn?tex2:tex1;
	}
    void OnGUI()
    {
        GUI.skin = guiSkin;
        if (GUI.Button(new Rect(20, 20, 300, 100), "翻轉"))
        {
            turn = !turn;
        }
    }
    IEnumerator test1()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//受權 
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            deviceName1 = devices[0].name;
            //設置攝像機攝像的區域 
            tex1 = new WebCamTexture(deviceName1, 1280, 720, 30);
            tex1.Play();//開始攝像 
        }
    }
    IEnumerator test2()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//受權 
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            deviceName2 = devices[1].name;
            //設置攝像機攝像的區域 
            tex2 = new WebCamTexture(deviceName2, 640, 480, 30);
            tex2.Play();//開始攝像 
        }
    } 
}

相關文章
相關標籤/搜索