Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

Help Wanted How to get world up vector in screen space

Discussion in 'Shaders' started by Nothke, Jun 29, 2020.

  1. Nothke


    Dec 2, 2012
    I'm trying to convert an "up" to screen space (in fragment) and I've just spent 2 hours trying to do it and my mind is just kinda running out of ideas, so I need some help. So, basically this:


    So imagine the black dots should be red directions, in screen space, so if the camera has 0 roll the vectors at the horizontal-center should have an x of 0 (this pic is only the left half of the screen). But it should work at any camera roll of course.

    The closest I got to is this, but it's incorrect:
    Code (CSharp):
    1. float3 viewUp = cross(viewDir, float3(0, 1, 0));
    2. float4 clipUp = mul(UNITY_MATRIX_V, viewUp);
    The reason I need the vector is to distort the reflection texture (which is 2D projected in screen space) anisotropically, so the vertical distortion is greater than the horizontal one.
  2. Namey5


    Jul 5, 2013
    One way would be to find the two end points of the vector in screen space and take the difference between them;

    Code (CSharp):
    1. //Find the world space position of both end points
    2. float3 p0 = worldPos;
    3. float3 p1 = worldPos + float3 (0,1,0);
    5. //Transform end points into clip space
    6. float4 cp0 = mul (UNITY_MATRIX_VP, float4 (p0, 1));
    7. float4 cp1 = mul (UNITY_MATRIX_VP, float4 (p1, 1));
    9. //Find screen space coords by remapping
    10. float2 uv0 = (cp0.xy / cp0.w) * 0.5 + 0.5;
    11. float2 uv1 = (cp1.xy / cp1.w) * 0.5 + 0.5;
    13. //Up vector is the difference between the points
    14. float2 up = uv1 - uv0;
    There's probably a smarter way, but that's the simplest way I could think of.
    Last edited: Jul 1, 2020 at 4:43 AM
    Nothke likes this.