Search Unity

Question What is the correct way to calculate the depth of objects under a mesh?

Discussion in 'Shader Graph' started by TheCelt, Nov 27, 2022.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
    I am so confused which node to use to calculate the depth under my water plane...its not clear which ones you should use to subtract to get the true distance.

    My current setup is like this:

    upload_2022-11-27_0-4-54.png

    I output to base so i can just see a white fade to see if its working but it doesn't and its buggy:

    a.gif

    What's the correct way to calculate this?
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    5,048
    Maybe use the world (or maybe object, but assume world) position instead of the view position?
     
  3. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
    But the depth is relative to camera. It didn't work for me.
     
  4. wwWwwwW1

    wwWwwwW1

    Joined:
    Oct 31, 2021
    Posts:
    767
    Hi, I think what you need is not depth (distance to camera), but vertical distance between two "points" (position.y related).

    There's no cube's position information in water plane shader.

    In this case, you can reconstruct the position (can be WorldSpace, NDC, ...) with scene depth (such as this thread).

    This node samples the camera depth texture. (stores opaque object's depth only)
    SceneDepthNode.jpg

    For each pixel (on water plane), this node returns the opaque scene (cube's) depth.

    (Pictures are hidden in spoiler blocks, sorry that the color is terrible)
    PointOnWaterPlane.jpg

    See, these two points have different depth.
    CubeDepth.jpg

    You can convert this opaque scene (cube's) depth to position so that it's possible to calculate vertical distance.
    "d" is the vertical distance.
    You can easily get the water plane point (pixel)'s position with a Position Node.
    VerticalDistance.jpg
     
  5. wwWwwwW1

    wwWwwwW1

    Joined:
    Oct 31, 2021
    Posts:
    767
    The range of vertical distance depends on the position type.

    If you need a more controllable range, I suggest reconstructing to "NDC space (-1..1)", rather than "WorldSpace".