√ 實現Unity遊戲畫面開啟裝置鏡頭之功能
1️⃣ 建立Raw Image物件。
「Hierachy底下右鍵」→「UI」→「Raw Image」。
(建立完畢後將之重新命名為:backdround。)
或於「GameObject」→「UI」→「Raw Image」。
2️⃣ 調整Raw Image物件。
調整Raw Image物件,使之延展至整個相機。
點選「Inspector」中的Rect Transform來設定(下圖紅框處圖示)。
選擇右下方紅框處的stretch x stretch。
將下圖紅框處之數值全設為0(Left、Top、Pos Z、Right、Bottom)。
3️⃣ Raw Image物件加入Component。
於Raw Image物件的「Inspector」→底下「Add Componebnt」→搜尋「Aspect Radio Fitter」。點選後即加入。
4️⃣ 新增並撰寫C# Script(在此命名為ScriptsCamera)。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScriptsCamera : MonoBehaviour { private bool camAvailable; private WebCamTexture backCam; private WebCamTexture frontCam; private Texture defaultBackground; public RawImage background; public AspectRatioFitter fit; // Use this for initialization private void Start () { defaultBackground = background.texture; WebCamDevice[] devices = WebCamTexture.devices; if (devices.Length == 0) { Debug.Log("No camera detected"); camAvailable = false; return; } for (int i = 0; i < devices.Length; i++) { // if (!devices [i].isFrontFacing) { //開啟後鏡頭 if (devices [i].isFrontFacing) { //開啟前鏡頭 backCam = new WebCamTexture (devices [i].name, Screen.width, Screen.height); } } if (backCam == null) { Debug.Log ("Unable to find back camera"); return; } backCam.Play(); background.texture = backCam; camAvailable = true; } // Update is called once per frame private void Update () { if (!camAvailable) return; float ratio = (float)backCam.width / (float)backCam.height; fit.aspectRatio = ratio; float scaleY = backCam.videoVerticallyMirrored ? -1f : 1f; // background.rectTransform.localScale = new Vector3 (1f, scaleY, 1f); //非鏡像 background.rectTransform.localScale = new Vector3 (-1f, scaleY, 1f); //鏡像 int orient = -backCam.videoRotationAngle; background.rectTransform.localEulerAngles = new Vector3 (0, 0, orient); } }
5️⃣ 設定Unity Camera。
於Camera的「Inspector」→底下「Add Component」→搜尋「ScriptsCamera」。點選後即加入。
或可直接拖曳,將腳本拖曳直接拖曳至Component處也可加入。
可以看到,原本的ScriptsCamera中的「Background」以及「Fit」都是None,將方才新增的Raw Image物件(background)直接拖曳至這兩處來指定,指定完如下圖。
6️⃣ 儲存場景(Scenes)
選擇「File」→「Save Scenes」。
7️⃣ 燒錄或點選Play即可在Game畫面中開啟該裝置的鏡頭。
留言列表