Unityシェーダースニペット集

スクリーン座標を取得する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct v2f
{
    float2 uv : TEXCOORD0;
}

v2f vert (
    float4 vertex : POSITION,
    float2 uv : TEXCOORD0,
    out float4 outpos : SV_POSITION // VPOSとSV_POSITIONを両方同時にフラグメントシェーダーに渡せないので、SV_POSITIONにout修飾子を付ける
)
{
    v2f o;
    o.uv = uv;
    outpos = UnityObjectToClipPos(vertex);
    return o;
}

fixed4 frag (v2f i, UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
{
    // screnPosは解像度の値(ex. 1920x1280)のような整数値なので0-1に変換する
    float2 screenPosNorm  = screenPos.xy / _ScreenParam.xy;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
fixed4 frag (v2f i, UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
{
    float3 cameraViewDir = -UNITY_MATRIX_V._m20_m21_m22;

    float3 cameraViewDirXZ = normalize(float3(cameraViewDir.x, 0, cameraViewDir.z));
    float3 cameraViewDirXY = normalize(float3(cameraViewDir.xy, 0));

    float moveH = atan2(cameraViewDirXZ.x, cameraViewDirXZ.z) / UNITY_PI * 2;
    float moveV = cameraViewDir.y;

    float4 screenPosNorm = float4(screenPos.xy / _ScreenParams.xy,0,0);


    // sample the texture
    fixed4 col = tex2D(_MainTex, float2(screenPosNorm.x + moveH, screenPosNorm.y + moveV ));

    clip( col.r - 0.5);
    //fixed4 col = float4(screenPosNorm.xy, 0, 0);
    return col;
}