在不用ar插件的情況下油吭,想要實(shí)現(xiàn)攝像機(jī)的效果击蹲,在這里可以使用 WebCamTexture
廢話不多說,先上代碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PhoneCamera : MonoBehaviour {
private bool camAvailable;
private WebCamTexture backCam;
private Texture defalutBackground;
public RawImage background;
public AspectRatioFitter fit;
private void Start()
{
defalutBackground = 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)
{
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;
}
void Update()
{
if(!camAvailable)
{
return;
}
// 獲取設(shè)備的長(zhǎng)寬比例
float ratio = (float)backCam.width / (float)backCam.height;
fit.aspectRatio = ratio;
// 如果視頻為鏡像婉宰,則y為-1 歌豺,即翻轉(zhuǎn)過來
float scaleY = backCam.videoVerticallyMirrored ? -1f : 1f;
background.rectTransform.localScale = new Vector3(1f,scaleY,1f);
// webcamTexture 旋轉(zhuǎn)z軸,負(fù)數(shù)時(shí)才為順時(shí)針
int orient = -backCam.videoRotationAngle;
background.rectTransform.localEulerAngles = new Vector3(0,0,orient);
}
}
該腳本拖給MainCamera
RawImage 設(shè)置如下
Paste_Image.png
這里要注意Canvas的 Scaler 設(shè)置為 Scale with Screen Size,填寫手機(jī)相對(duì)應(yīng)的分辨率
over ~心包!