Search Unity

Shader Screenspace Position Issue

Discussion in 'Shaders' started by Wuceng, Oct 31, 2020.

  1. Wuceng

    Wuceng

    Joined:
    Dec 18, 2018
    Posts:
    9
    I am trying to apply a post processing effect to all pixels outside of a certain range of my character.

    This is the shader code I have so far for converting my players position into screenspace and testing each fragment against it.
    Code (CSharp):
    1. //Worldspace Player Pos
    2. float4 _PlayerPosition;
    3.  
    4. float4 Frag(VaryingsDefault i) : SV_Target
    5. {
    6.     float4 playerPositionClipSpace = mul(unity_MatrixVP,_PlayerPosition);
    7.     float3 playerPositionScreenSpace = playerPositionClipSpace.xyz / playerPositionClipSpace.w;
    8.     playerPositionScreenSpace = playerPositionScreenSpace * 0.5 + 0.5;
    9.  
    10.     float4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord);
    11.     if (length(playerPositionScreenSpace.xy - i.texcoord) >= 0.1f)
    12.     {
    13.         color.rgb = float3(0,0,0);
    14.     }
    15.     return color;
    16. }
    My problem is, that the resulting circle is somehow not centered on the given character position.
    upload_2020-10-31_2-25-25.png

    Would appreciate if someone has an idea for why that may be the case :)
     
  2. Wuceng

    Wuceng

    Joined:
    Dec 18, 2018
    Posts:
    9
    Okay I figured it out on my own. The issue was that when running on DirectX Texture Coordinates need to be flipped on the y-axis.
    https://docs.unity3d.com/Manual/SL-PlatformDifferences.html has more information

    This is how I did it in case anyone else runs into this issue and is confused.

    Code (CSharp):
    1.  if (length(playerPositionNDC - float2(i.texcoord.x,1-i.texcoord.y)) >= 0.1f)
    upload_2020-10-31_10-0-12.png
    The result is now correctly centered on the playerPosition.