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
        }
    }
}

效果

相关推荐
郝学胜-神的一滴8 小时前
中级OpenGL教程 005:为球体&平面注入法线灵魂
c++·unity·图形渲染·three.js·opengl·unreal
XX風1 天前
OpenGL 离屏多重采样抗锯齿 (Off-screen MSAA)
图形渲染
mxwin3 天前
unity shader中 ddx ddy是什么
unity·游戏引擎·shader
郝学胜-神的一滴3 天前
[简化版 GAMES 101] 计算机图形学 08:三角形光栅化上
c++·unity·游戏引擎·godot·图形渲染·opengl·unreal
RReality3 天前
【Unity Shader URP】视差贴图 实战教程
ui·平面·unity·游戏引擎·图形渲染·贴图
hele_two4 天前
VS Code + CMake 调用 SDL2 & SDL2_image 完整编译教程(Windows 平台)
c++·windows·vscode·图形渲染
hele_two4 天前
SDL2高效画实心圆的算法(一)
c++·算法·图形渲染
XX風4 天前
OpenGL Framebuffer及其附件使用详解
图形渲染
梵尔纳多4 天前
OpenGL 实例化
c++·图形渲染·opengl
mxwin4 天前
Unity SetPassCall和DrawCall的区别是什么
unity·游戏引擎·shader