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.