VR项目里面对某个物体截图

项目需求:类似小孩头戴HTC玩积木,最终对积木四面八方截图

技术难点:HTC会自动关联场景中摄像机,即使关闭头显摄像机,头显射线机会自动关联场景中被激活的相机,相机的视角无法固定。

最终解决方案:
1、创建多个摄像机,调整角度一直朝向想要截图的模型,各个方位的;
2、创建多个Render Texture,放到每个摄像机上;
3、通过获取摄像机渲染的内容并保存图片来满足截图需求,代码如下;

using UnityEngine;
using System.Collections;
using System;
using UnityEditor;

/// 
/// 输出相机渲染图片
/// 
public class  CameraSnapshot : MonoBehaviour
{
    [SerializeField]
    private Camera[] securityCamera;

    RenderTexture securityCameraTexture;

    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            //截图成功
            StartCoroutine(SaveCameraView());
        }
    }

    /// 
    /// 开始截取
    /// 
    /// The camera view.
    public IEnumerator SaveCameraView ()
    {
        yield return new WaitForEndOfFrame ();

        RenderTexture rendText = RenderTexture.active;

        foreach (var item in securityCamera) {
            
            RenderTexture.active = item.targetTexture;
            item.Render ();

            Texture2D cameraImage = new Texture2D (item.targetTexture.width, item.targetTexture.height, TextureFormat.RGB24, false);
            
            cameraImage.ReadPixels (new Rect (0, 0, item.targetTexture.width, item.targetTexture.height), 0, 0);
            
            cameraImage.Apply ();

            RenderTexture.active = rendText;
            
            byte[] bytes = cameraImage.EncodeToPNG ();

            System.IO.File.WriteAllBytes(Application.dataPath + item.name + "_image.png", bytes);
        }
        AssetDatabase.Refresh ();
    }

}

4、因场景中会出现多个摄像机,全都实时渲染,程序DrawCall直接突破2000+,这时需要先对摄像机取消激活,当需要截图的时候打开;

你可能感兴趣的:(VR项目里面对某个物体截图)