Unity3D Shader:景深

本文探讨了如何使用Unity3D的Shader技术来实现逼真的景深效果,通过C#代码和 shader 代码的结合,为游戏场景增添视觉层次感。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#代码:

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

public class JingShen : MonoBehaviour {

    public Material mat;

    [Range(0f, 100f)]
    public float focalDistance = 10;//焦点距离

    [Range(0, 100)]
    public float nearBlurScale = 0;//近距离模糊缩放

    [Range(0,1000f)]
    public float farBlurScale = 50;//远距离模糊缩放

    public int downSample = 1;//分辨率降低值

    public int sampleScale = 1;//采样半径


    private void OnEnable()
    {
        GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;//开启深度
    }
    private void OnDisable()
    {
        GetComponent<Camera>().depthTextureMode &= ~DepthTextureMode.Depth;//关闭深度
    }
    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        Mathf.Clamp(focalDistance, transform.GetComponent<Camera>().nearClipPlane, transform.GetComponent<Camera>().farClipPlane);//限制焦点距离在摄像机最近裁剪面和最远裁剪面
        RenderTexture temp1 = RenderTexture.GetTemporary(source.width >> downSample, source.height >> downSample, 0, source.format);//降低分辨率
        RenderTexture temp2 = RenderTexture.GetTemporary(source.width >> downSample, source.height >> downSample, 0, source.format);
        Graphics.Blit(source, temp1);

        mat.SetVector("_offset", new Vector4(0, sampleScale, 0, 0));//垂直取值
        Graphics.Blit(temp1, temp2, mat,0);
        mat.SetVector("_offset", new Vector4(sampleScale, 0, 0, 0));//水平取值
        Graphics.Blit(temp2, temp1, mat,0);

        mat.SetTexture("_BlurTex", temp1);
        mat.SetFloat("_focalDistance", FocalDistance(focalDistance));
        mat.SetFloat("_nearBlurScale", nearBlurScale);
        mat.SetFloat("_farBlurScale", farBlurScale);

        Graphics.Blit(source, destination, mat, 1);

        RenderTexture.ReleaseTemporary(temp1);
    
增加层级一/二/3J………………………………………………………………………………Add Lv1/2/3 通道透明一/二/3J………………………………………………………………………………Alpha Blend Lv1/2/3 (一级在最下层,3J在最上层,这些和细微遮挡有关) 置换扭曲(扭曲自身)……………………………………………………………………………Displacement Map Add 溶解消失……………………………………………………………………………………………Dissolve 溶解消失(有描边)………………………………………………………………………………Dissolve Coloredge 溶解消失(从红色通道)…………………………………………………………………………Dissolve Simple 环境扭曲(带扰动)………………………………………………………………………………Distortion 环境扭曲(从贴图,在有环境的时候扭曲,必须有背景)……………………………………Distortion Bump 透明描边……………………………………………………………………………………………Falloff Alpha 描边+贴图…………………………………………………………………………………………Falloff Texture 遮罩增加……………………………………………………………………………………………Mask Add 遮罩透明……………………………………………………………………………………………Mask AlphaBlend
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值