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

UNITY_MATRIX_V and camera position

Discussion in 'Shaders' started by arkano22, Mar 1, 2018.

  1. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    728
    Hi folks!

    In a shader, I'd expect -UNITY_MATRIX_V[3].xyz to contain the camera's world space position (just like _WorldSpaceCameraPos).

    Experiments show that it is always zero, tough. _WorldSpaceCameraPos contains the expected values. I would expect both to be pretty much interchangeable during normal rendering passes (but not when rendering shadows). Can anyone explain this behavior?
     
    Last edited: Mar 1, 2018
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    9,150
    UNITY_MATRIX_V._m03_m13_m23
     
  3. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    728
    Exactly same results as -UNITY_MATRIX_V[3].xyz, at least in my tests. (It accesses the exact same entries in the matrix, so I don't see how it would yield different results...)

    I'm simply getting a ray in world space, from the camera to each vertex of a quad. Works correctly when using _WorldSpaceCameraPos, does not when grabbing the position from the view matrix.

    Bummer: I have to do this in a shadow caster pass, so I don't have _WorldSpaceCameraPos available. Need to find the camera position some other way.
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    9,150
    UNITY_MATRIX_V[3].xyz == UNITY_MATRIX_V._m30_m31_m32, not UNITY_MATRIX_V._m03_m13_m23

    Though those still won't match quite right as the z axis of UNITY_MATRIX_V is inverted compared to _WorldSpaceCameraPos.z and Unity's world space coordinates in general. That also means that _WorldSpaceCameraPos and even float3(UNITY_MATRIX_V._m03_m13, -UNITY_MATRIX_V._m23) will only match if there's no rotation.

    The inverse view matrix's third column should match _WorldSpaceCameraPos.xyz though:
    UNITY_MATRIX_I_V._m03_m13_m23 == _WorldSpaceCameraPos.xyz
     
    Last edited: Mar 1, 2018
  5. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    728
    You're absolutely right. Thanks a lot! I didn't even know the inverse view matrix was accessible from within a shader.
     
unityunity