Unity Shader 获取场景深度图

获取场景深度图,需要明白场景中的物体是否是透明物体,透明物体和不透明物体的获取方式不一样。

一、获取场景中不透明物体深度图

1、创建Render Texture

2、创建Shader脚本

Shader "Custom/Depth" 
{  
	SubShader {  
		
		Pass{  
			CGPROGRAM  
			#pragma vertex vert  
			#pragma fragment frag  
			#include "UnityCG.cginc"  

			sampler2D _CameraDepthTexture;  
			struct v2f 
			{  
			   float4 pos : SV_POSITION;  
			   float4 scrPos:TEXCOORD1;  
			};  

			v2f vert (appdata_base v)
			{  
			   v2f f;  		  
			   f.pos = UnityObjectToClipPos (v.vertex);  
			   f.scrPos=ComputeScreenPos(f.pos);  
			   return f;  
			}  
			  
			half4 frag (v2f f) : COLOR
			{  
			   float depthValue =Linear01Depth (tex2Dproj(_CameraDepthTexture,UNITY_PROJ_COORD(f.scrPos)).r);
			   return half4(depthValue,depthValue,depthValue,1);  
			}  
			ENDCG  
		}  
	}  
	FallBack "Diffuse"  
}  

3、创建材质,修改shader为上面的shader

4、创建相机,创建c#脚本,保存深度图

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class depth : MonoBehaviour
{
    // Start is called before the first frame update
    private Camera m_Camera;
    public Material Mat;
    public RenderTexture DepthRenderTexture;
    string m_DepthMapName;
    void Start()
    {
        m_Camera = gameObject.GetComponent<Camera>();
        m_Camera.depthTextureMode = DepthTextureMode.Depth;
        m_DepthMapName = "depth.png";
    }
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (null != Mat)
        {
            Graphics.Blit(source, DepthRenderTexture, Mat);
            saveDepthMap();
        }
    }

    private void saveDepthMap()
    {
        int Width = DepthRenderTexture.width;
        int Height = DepthRenderTexture.height;
        Texture2D texture2D = new Texture2D(Width, Height);
        var previous = RenderTexture.active;
        RenderTexture.active = DepthRenderTexture;
        texture2D.ReadPixels(new Rect(0, 0, Width, Height), 0, 0);
        RenderTexture.active = previous;
        texture2D.Apply();
        byte[] Data = texture2D.EncodeToPNG();
        FileStream file = File.Open(m_DepthMapName, FileMode.Create, FileAccess.Write);
        BinaryWriter writer = new BinaryWriter(file);
        writer.Write(Data);
        file.Close();
    }
}

在工程目录下面可以看到深度图

参考文章:https://www.jianshu.com/p/72c07b0bbaa5

 

二、场景中透明物体深度图获取

待写

 

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值