Question by
michelangeloevil · Mar 14, 2018 at 03:30 PM ·
shadershadersshader programmingshader writing
How do I get the fragment position in world coordinates?
Right now I am trying to write a transparency shader that is able to slice the world by setting its transparency. But I really can not figure out how to get the fragments y-Position in world coordinates. Right now I get is screen coordinates only.
Pass
{
CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata{
float4 position : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Transparency;
float _Slice;
v2f vert(appdata vertex)
{
v2f output;
output.position = UnityObjectToClipPos(vertex.position);
output.uv = TRANSFORM_TEX(vertex.uv, _MainTex);
return output;
}
fixed4 frag(v2f input) : SV_TARGET
{
fixed4 col = tex2D(_MainTex, input.uv);
col.a = _Transparency;
//clip(_Slice - input.position.y);
if(_Slice < input.position.y){
col.a = 0;
}
return col;
}
ENDCG
Comment
Best Answer
Answer by michelangeloevil · Mar 14, 2018 at 04:32 PM
Use another variable in your vertex to fragment data struct. worldSpacePos = mul(unity_ObjectToWorld, vertex.position); Then use worldSpacePos in your fragment shader.
Pass
{
CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata{
float4 position : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
float4 worldSpacePos : TEXCOORD1;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Transparency;
float _Slice;
v2f vert(appdata vertex)
{
v2f output;
output.position = UnityObjectToClipPos(vertex.position);
output.worldSpacePos = mul(unity_ObjectToWorld, vertex.position);
output.uv = TRANSFORM_TEX(vertex.uv, _MainTex);
return output;
}
fixed4 frag(v2f input) : SV_TARGET
{
fixed4 col = tex2D(_MainTex, input.uv);
col.a = _Transparency;
//clip(_Slice - input.position.y);
if(_Slice < input.worldSpacePos.y){
col.a = 0;
}
return col;
}
ENDCG
}
Your answer
Follow this Question
Related Questions
Operate the shader, rotate the material 90 degrees 0 Answers
How much operations does tex2d func take? 0 Answers
Reversed UV Light with 2D PointLight (shader graph) 0 Answers
Shader - SV_Target 1 Answer