- Home /
How to get the screen position in an unlit shader.
Hi, I'm writing a shader in unity that isn't based on "#pragma surface surf Lambert". How do I get the current pixel screen position in the fragment program? I need it to be in pixels (not between 0 and 1 or -1 and 1). Here's my shader code:
Shader "selectedFace"
{
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
float4 vert(float4 vertexPosition:POSITION):POSITION
{
return mul(UNITY_MATRIX_MVP,vertexPosition);
}
float4 frag(void):COLOR
{
//GET SCREEN POSITION HERE!!!
return float4(0.75,1.0,0.0,1.0);
}
ENDCG
}
}
}
Thanks :D
I have a similar problem... $$anonymous$$VP mens $$anonymous$$odel rotation, followed by view, then the perspective transform, converting it into "Clip space" -1 to 1 . I assumes this clip space to be the size of the screen, but it seems to be more like the size / bounds of each object.
I have got somewhat close, by subtracting vertexposition from worldcameraposition, then doing a partial transform... not the full $$anonymous$$VP... but the result is somewhat saddle shaped... curved, and not an exact match.... not sure how to get it perfect :/
void vert (inout appdata_full v, out Input o) {
UNITY_INITIALIZE_OUTPUT(Input,o);
o.worldPos = mul (_Object2World, v.vertex);
float3 relPos = o.worldPos - _WorldSpaceCameraPos;
float dist = length (relPos);
o.locPos = mul (UNITY_$$anonymous$$ATRIX_V, o.worldPos.xyz); // just V
o.locPos = o.locPos /dist; //true space perspective, ins$$anonymous$$d of /z try this if no P on the $$anonymous$$VP transform
o.locPos *= _$$anonymous$$etaScalar; //scalar param, so I can experiment with it
}
Answer by tanoshimi · Jun 19, 2016 at 07:06 AM
Define a new member in the structure passed from your vertex to fragment shader, say, scrPos
. Assign it an unused TEXCOORD semantic.
Populate it in the vertex program using the ComputeScreenPos macro:
v2f vert(appdata_full v)
{
o.scrPos = ComputeScreenPos(v.pos);
...
And then use it as follows in the fragment shader:
fixed4 frag(v2f i) : COLOR
{
float2 screenPosition = (i.scrPos.xy/i.scrPos.w);
thanks $$anonymous$$uch tanoshimi !, that was almost it... just needed this to work... o.locPos=mul(UNITY_$$anonymous$$ATRIX_$$anonymous$$VP,v.vertex); o.locPos = ComputeScreenPos(o.locPos);