美文网首页
unity—— device camera

unity—— device camera

作者: OneMore2018 | 来源:发表于2017-07-03 13:55 被阅读104次

    在不用ar插件的情况下,想要实现摄像机的效果,在这里可以使用 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;
        }
      // 获取设备的长宽比例
        float ratio = (float)backCam.width / (float)backCam.height;
        fit.aspectRatio = ratio;
    

    // 如果视频为镜像,则y为-1 ,即翻转过来
    float scaleY = backCam.videoVerticallyMirrored ? -1f : 1f;
    background.rectTransform.localScale = new Vector3(1f,scaleY,1f);
    // webcamTexture 旋转z轴,负数时才为顺时针
    int orient = -backCam.videoRotationAngle;
    background.rectTransform.localEulerAngles = new Vector3(0,0,orient);
    }
    }
    该脚本拖给MainCamera
    RawImage 设置如下

    Paste_Image.png
    这里要注意Canvas的 Scaler 设置为 Scale with Screen Size,填写手机相对应的分辨率
    over ~!

    相关文章

      网友评论

          本文标题:unity—— device camera

          本文链接:https://www.haomeiwen.com/subject/wzwacxtx.html