Version: Unity 6.0 (6000.0)
语言 : 中文
在自定义 URP 着色器中变换位置
在自定义 URP 着色器中使用光照

在自定义 URP 着色器中使用摄像机

要在自定义通用渲染管线 (URP) 着色器中使用摄像机,请执行以下步骤:

  1. 在着色器文件中的 HLSLPROGRAM 中添加 #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"Core.hlsl 文件将导入 ShaderVariablesFunction.hlsl 文件。
  2. 使用 ShaderVariablesFunction.hlsl 文件的以下方法之一。
方法 语法 描述
GetCameraPositionWS float3 GetCameraPositionWS() 返回摄像机的世界空间位置。
GetScaledScreenParams float4 GetScaledScreenParams() 返回屏幕的宽度和高度(以像素为单位)。
GetViewForwardDir float3 GetViewForwardDir() 返回视图在世界空间中的前进方向。
IsPerspectiveProjection bool IsPerspectiveProjection() 如果摄像机投影设置为透视,则返回 true
LinearDepthToEyeDepth half LinearDepthToEyeDepth(half linearDepth) 将线性深度缓冲区值转换为视图深度。请参阅摄像机和深度纹理以了解更多信息。
TransformScreenUV void TransformScreenUV(inout float2 screenSpaceUV) 如果 Unity 使用上下颠倒的坐标空间,则翻转屏幕空间位置的 y 坐标。您还可以输入 uv 和屏幕高度作为 float,因此该方法会输出按屏幕大小缩放的位置(以像素为单位)。

示例

以下 URP 着色器使用代表从表面到摄像机方向的颜色绘制对象表面。

Shader "Custom/DirectionToCamera"
{
    SubShader
    {
        Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }

        Pass
        {
            HLSLPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
                float2 uv: TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionCS  : SV_POSITION;
                float2 uv: TEXCOORD0;
                float3 viewDirection : TEXCOORD2;
            };

            Varyings vert(Attributes IN)
            {
                Varyings OUT;

                // Get the positions of the vertex in different coordinate spaces
                VertexPositionInputs positions = GetVertexPositionInputs(IN.positionOS);
                OUT.positionCS = positions.positionCS;

                // Get the direction from the vertex to the camera, in world space
                OUT.viewDirection = GetCameraPositionWS() - positions.positionWS.xyz;

                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                // Set the fragment color to the direction vector
                return float4(IN.viewDirection, 1);
            }
            ENDHLSL
        }
    }
}

其他资源

在自定义 URP 着色器中变换位置
在自定义 URP 着色器中使用光照