Unity开启摄像头并铺满屏幕

可能比较常用,但是每次都需要重新写,这次直接把这个贴在这里,下次直接复制粘贴。

主要功能:打开WebCamera,在空间中创建Panel,用于显示相机画面。Panel做了比例适配,可以正确显示图像并铺满屏幕。Panel放在相机最远处,避免与其他模型穿插

using UnityEngine;
/*
create by keefor On 20200106
*/
[RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))]
public class CameraPlay : MonoBehaviour
{
    [HideInInspector]
    public WebCamTexture camtex;
    private Material mat;
    private Camera cam;

    private static CameraPlay inst;
    public static CameraPlay Inst
    {
        get
        {
            if (inst == null)
            {
                var pp = GameObject.CreatePrimitive(PrimitiveType.Quad);
                pp.name = "WebCamera";
                Destroy(pp.GetComponent<Collider>());
                inst = pp.AddComponent<CameraPlay>();
            }
            return inst;
        }
    }


    void Awake()
    {
        inst = this;

        UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.Camera);
        WebCamDevice[] cd = WebCamTexture.devices;
        camtex = new WebCamTexture(cd[0].name,  480,320,15);//考虑到性能问题这里选择了小尺寸
        var render = this.GetComponent<Renderer>();
        render.material = mat = new Material(Shader.Find("Unlit/Texture"));
        cam = Camera.main;
        if (cam == null) cam = Camera.allCameras[0];
        transform.SetParent(cam.transform);
        transform.localPosition = new Vector3(0, 0, cam.farClipPlane);
    }

    void OnEnable()
    {
        camtex.Play();
        mat.mainTexture = camtex;
        var lt = cam.ScreenToWorldPoint(new Vector3(0, 0, cam.farClipPlane));
        var rb = cam.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, cam.farClipPlane));
        Debug.Log(lt + ":" + rb);
        var sc = new Vector3(Mathf.Abs(rb.x - lt.x), Mathf.Abs(lt.y - rb.y), 1);
        var ratio = sc.x / sc.y;
        var scratio = (float)camtex.width / camtex.height;
        if (ratio > scratio)
        {
            sc.y = sc.x / scratio;
        }
        else
        {
            sc.x = sc.y * scratio;
        }
        transform.localScale = sc;
    }

    void OnDisable()
    {
        camtex.Stop();
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值