Search Unity

Player position in world space to screen position.

Discussion in 'Shaders' started by DTD, Dec 10, 2018.

  1. DTD

    DTD

    Joined:
    Jun 14, 2017
    Posts:
    2
    im working on making a shader that dissolve objects that are in front of players. my problem is that i dont know how to make the mask in screen space to follow the player position, since the world coordinates are not the same as screen space coordinates. what do i do? (im using Amplify shader)
    upload_2018-12-10_18-3-1.png
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    What you need to do is transform the world space position into screen space position.


    You're response to to reading that might be "yeah, I know", but it's also kind of the entire answer. Well, to be fair, I guess there are two steps this this.

    Step 0: Set player's world position vector on the material using mat.SetVector() or using Shader.SetGlobalVector() via script (I assume you're already doing this).
    Step 1: Get the clip space position of that position.
    Step 2: Get the screen space position of that position & apply perspective divide.​

    If you were writing shaders in HLSL it would look like this:

    float4 playerClipPos = mul(UNITY_MATRIX_VP, float4(_PlayerPosition.xyz, 1.0));
    float4 playerScreenPos = ComputeScreenPos(playerClipPos);
    playerScreenPos.xy /= playerScreenPos.w;


    And you're done. The UNITY_MATRIX_VP is the view projection matrix. You should be able to access that via the Common Transform Matrices node. The ComputeScreenPos function also exists as a node you can use directly, which appears to have an option to apply the perspective divide (i.e.: divide by w). I don't use Amplify so I couldn't answer the rest of how to translate that code to ASE.

    I'd recommend asking if the official ASE forums rather than here.
    http://amplify.pt/forum/viewforum.php?f=23
     
  3. DTD

    DTD

    Joined:
    Jun 14, 2017
    Posts:
    2
    Hey thx for the reply. i have been fiddling around with this but dont know how translate the HLSL code to node based... ill try ask on amplify forum =)