生活随笔
收集整理的這篇文章主要介紹了
如何在unity中调用电脑或安卓自带的摄像机
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
如何在unity中調(diào)用電腦自帶攝像機(jī)
(申明:此問題的文章在其他網(wǎng)站也有,不過作者敘述不夠詳細(xì),導(dǎo)致一些小的bug不容易被新人發(fā)現(xiàn),故在原作者基礎(chǔ)上進(jìn)行了完善。) 1.新建一個(gè)unity3d 項(xiàng)目,在場(chǎng)景中新建Resources文件夾》Material文件夾,在文件夾中新建一個(gè)材質(zhì)CameraPlane;并且材質(zhì)球的Shader:Unlit/Texture .
2.在場(chǎng)景中新建一個(gè)Camera (注意保留新項(xiàng)目自帶的攝像機(jī);注:unity老的版本似乎不會(huì)在新建項(xiàng)目時(shí)自動(dòng)生成一個(gè)攝像機(jī),那么老版本的用戶請(qǐng)先自己建一個(gè)攝像機(jī),然后進(jìn)行上面的操作),并且把對(duì)象重新命名為WebCamera,注意現(xiàn)在場(chǎng)景中有兩個(gè)攝像機(jī),這時(shí)就涉及到誰(shuí)顯示畫面的問題了,解決方法是將新建的攝像機(jī)禁用 ,在WebCamera下面添加一個(gè)子對(duì)象Plane[重命名為CameraPlaneMeshRender,需要MeshRender,把第一步操作的材質(zhì)球附加上。
3.到這一步,就是比較重點(diǎn)了,在WebCamera上新建一個(gè)腳本(WebCameraManager.cs),主要作用是處理調(diào)用外部攝像頭,并且顯示攝像的內(nèi)容 ###代碼`using System.Collections; using System.Collections.Generic; using UnityEngine;
public class WebCanamerManager : MonoBehaviour {
public string DeviceName;
public Vector2 CameraSize;
public float CameraFPS; //在計(jì)算機(jī)圖像領(lǐng)域中,“FPS”是詞組“Frames Per Second”的縮寫。“Frames Per Second”在計(jì)算機(jī)圖像范疇內(nèi)被翻譯為:“每秒傳輸幀數(shù)”。更確切的解釋,就是“每秒中填充圖像的幀數(shù)(幀/秒)“。WebCamTexture _webCameraTexture; //接收返回的圖片數(shù)據(jù)
public GameObject Plane;//作為顯示攝像頭的面板void OnGUI()
{if (GUI.Button(new Rect(100, 100, 100, 100), "初始化相機(jī)")){StartCoroutine("InitCameraCor");//開始協(xié)程,意思就是啟動(dòng)一個(gè)輔助的線程}//添加一個(gè)按鈕來控制攝像機(jī)的開和關(guān)if (GUI.Button(new Rect(100, 250, 100, 100), "ON/OFF")){if (_webCameraTexture != null && Plane != null){if (_webCameraTexture.isPlaying)StopCamera();elsePlayCamera();}}if (GUI.Button(new Rect(100, 450, 100, 100), "Quit")){Application.Quit();//退出}}public void PlayCamera()
{Plane.GetComponent<MeshRenderer>().enabled = true;_webCameraTexture.Play();
}public void StopCamera()
{Plane.GetComponent<MeshRenderer>().enabled = false;_webCameraTexture.Stop();
}/// <summary>
/// 初始化攝像頭
/// </summary> public IEnumerator InitCameraCor() //定義一個(gè)協(xié)程
{yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);if (Application.HasUserAuthorization(UserAuthorization.WebCam)){WebCamDevice[] devices = WebCamTexture.devices;DeviceName = devices[0].name;_webCameraTexture = new WebCamTexture(DeviceName, (int)CameraSize.x, (int)CameraSize.y, (int)CameraFPS);Plane.GetComponent<Renderer>().material.mainTexture = _webCameraTexture;Plane.transform.localScale = new Vector3(1, 1, 1);_webCameraTexture.Play();}
}
}`
好的下面就大功告成了!!!
總結(jié)
以上是生活随笔 為你收集整理的如何在unity中调用电脑或安卓自带的摄像机 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。