Camera-facing UVs

Ok so the problem was that when I cleaned up the shader I also forgot that you can’t just use the POSITION semantic from the vertex shader and expect to be able to use the clip position in the fragment shader. It mostly works in the “Scene” tab (which is what I tested before posting, also why it might appear to work sometimes and not others), but not in the “Game”. so I just changed the code to store the clip space in TEXCOORD0 and that appears to work for both (but the texture is inverted along the Y axis in the “Scene” tab, because Unity is silly like that).

Here’s the new code. Sorry about the formatting, still haven’t found the best way to copy code into this forum:

Shader “Custom/screenSpaceUV” {
Properties {
_MainTex (“Color Texture”, 2D) = “white” {}
_SSUVScale(“UV Scale”, Range(0,10)) = 1
}

CGINCLUDE
	sampler2D _MainTex;
	float _SSUVScale;

	struct appdata {
		float4 vertex : POSITION;
	};

	struct v2f {
		float4 pos : POSITION;
		float4 pos2: TEXCOORD0;
	};

	float2 GetScreenUV(float2 clipPos, float UVscaleFactor)
	{
		float4 SSobjectPosition = mul (UNITY_MATRIX_MVP, float4(0,0,0,1.0)) ;
		float2 screenUV = float2(clipPos.x,clipPos.y);
		float screenRatio = _ScreenParams.y/_ScreenParams.x;

		screenUV.x -= SSobjectPosition.x/(SSobjectPosition.w);
		screenUV.y -= SSobjectPosition.y/(SSobjectPosition.w); 

		screenUV.y *= screenRatio;

		screenUV *= 1/UVscaleFactor;
		screenUV *= SSobjectPosition.z;

		return screenUV;
	};


ENDCG

SubShader {
  	Tags { "RenderType" = "Opaque" }

  	Pass 
	{
		CGPROGRAM
		#pragma vertex vert
		#pragma fragment frag
		#include "UnityCG.cginc"

		v2f vert(appdata v) {				
			v2f o;
			o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
			o.pos2 = o.pos;

			return o;
		}		

		half4 frag(v2f i) :COLOR 
		{ 				
			float2 screenUV = GetScreenUV(i.pos2.xy/ i.pos2.w, _SSUVScale);
			half4 screenTexture = tex2D (_MainTex, screenUV);

			return screenTexture; 
		} 
		ENDCG				 
	}

} 
Fallback "Diffuse"

}

Let me know if that works better for you.

1 Like