Unity Shader unity文档学习笔记(十八):unity雾效原理

看很多文章用近平面远平面组成矩阵后转到裁剪空间下通过Z值来解,实际更简单的方式可以直接通过判断距离来实现

FogMgr控制远近面

复制代码
public class TestFog : MonoBehaviour
{
    public int startDis = 0;
    public int endDis = 50;

    public Vector4 fogParam;

    public void Awake()
    {
        fogParam = new Vector4(startDis, endDis, 0, 0);
        Shader.SetGlobalVector("DisFog", fogParam);
    }
}

Test_Fog.cginc 库

复制代码
#ifndef TEST_FOG
#define TEST_FOG

float4 DisFog;

float MyComputerFog(float3 worldPos)
{
    float fogFactory = distance(worldPos.xz, _WorldSpaceCameraPos.xz)/(DisFog.y - DisFog.x);
    return fogFactory;
}

#endif

TestFog shader

复制代码
Shader "Test/TestFog"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _FogColor ("FogColor", Color) = (1, 1, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

		    #include "UnityCG.cginc"
            #include "Test_Fog.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
               	float3 worldPos : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            float4 _FogColor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                fixed4 fogColor = _FogColor * MyComputerFog(i.worldPos);
                return lerp(col, fogColor, 0.5);
            }
            ENDCG
        }
    }
}

效果

相关推荐
allenjiao3 天前
WebGPU vs WebGL:WebGPU什么时候能完全替代WebGL?Web 图形渲染的迭代与未来
前端·图形渲染·webgl·threejs·cesium·webgpu·babylonjs
BoBoZz193 天前
TriangleStrip连续三角带
python·vtk·图形渲染·图形处理
jinxinyuuuus5 天前
Wallpaper Generator:高精度图形渲染中的WebGPU与色彩感知工程
程序人生·生活·图形渲染
杨筱毅5 天前
【底层机制】Android图形渲染体系深度解析:VSync信号机制
android·图形渲染·底层机制
雨泽‎6 天前
Unity在URP中开启后处理导致RenderTexture存在背景
unity·游戏引擎·图形渲染
1***81536 天前
HarmonyOS图形渲染
图形渲染
BoBoZz197 天前
CellTypeSource
python·vtk·图形渲染·图形处理
Renderbus瑞云渲染农场7 天前
什么叫云渲染?云渲染是干嘛的?
3d·图形渲染·3dsmax
不会写DN8 天前
[特殊字符]开班会时由于太无聊,我开发了一个小游戏……
程序人生·信息可视化·职场和发展·交互·图形渲染·学习方法·高考
在路上看风景8 天前
1.7 C#传递参数给Shader
shader