0
\$\begingroup\$

I am currently trying to sample a texture in screen space. This works well :

float4 positionCS = vertexInput.positionCS / vertexInput.positionCS.w;
screenPos = ComputeScreenPos(positionCS).xy;
float aspect = _ScreenParams.x / _ScreenParams.y;
screenPos.x = screenPos.x * aspect;

But I would like to be able to constrain uv position and scale based on object's position and distance from camera. I found some example but I also faced some issues and for the moment I don't see how to fix them. Here's the code :

float4 positionCS = vertexInput.positionCS / vertexInput.positionCS.w;
screenPos = ComputeScreenPos(positionCS).xy;
float aspect = _ScreenParams.x / _ScreenParams.y;
screenPos.x = screenPos.x * aspect;

float4 originCS = TransformObjectToHClip(float3(0.0, 0.0, 0.0));
originCS = originCS / originCS.w;
float2 originSPos = ComputeScreenPos(originCS).xy;
originSPos.x = originSPos.x * aspect;
screenPos = screenPos - originSPos;

// You can match object's distance like this
float3 cameraPosWS = GetCameraPositionWS();
float3 originPosWS = TransformObjectToWorld(float4(0.0, 0.0, 0.0, 1.0));
float d = distance(float4(0.0, 0.0, 0.0, 0.0), cameraPosWS - originPosWS);
screenPos *= d;

And here's the issue I am facing. You can notice that when the object is near screen edges the texture starts to move. Is there a way to avoid that ?

https://thumbs.gfycat.com/HairySpryArawana-mobile.mp4

I am using URP but this doesn't really matter.

\$\endgroup\$
  • \$\begingroup\$ just use them inside the vertex shader.can I answer with shadergraph? \$\endgroup\$ – Seyed Morteza Kamali Jun 2 at 10:12
  • \$\begingroup\$ Thanks for the answer. All those are computed in the vertex shader :( But if you achieve to make this work without my issues, I would love to see the graph yeah ! \$\endgroup\$ – MaT Jun 2 at 10:16
  • \$\begingroup\$ I think the phenomenon you're seeing is because, as a sphere moves further from the axis of a perspective camera, its projected shape becomes increasingly elliptical. So the leading edge of the shape that you see in your screen really is more pixels away from the shape's center, due to this elongation, leading to more repeats of the texture being visible along that stretched axis. The texture itself isn't moving - the edge of the sphere is stretching out to encompass more of the texture. \$\endgroup\$ – DMGregory Jun 2 at 14:00
  • \$\begingroup\$ Hmm this makes sens but is there a way to get rid of this ? \$\endgroup\$ – MaT Jun 2 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.