カスタムのユニバーサルレンダーパイプライン (URP) シェーダーでカメラを使用するには、以下の手順に従います。
HLSLPROGRAM に #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" を加えます。Core.hlsl ファイルは ShaderVariablesFunction.hlsl ファイルをインポートします。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
}
}
}