- Home /
Get absolute position of vertex in shader
I am trying to clip my object based on an absolute plane or distance, however I am unable to get a value that is not directly tied to the camera position and rotation.
here’s basically what I want to achieve, but it should remain the same when camera moves around it.
To see what happens when the camera rotates, here’s an animated version:
I thought this would be a rather simple thing to do, but shaders are still strange for me.
Here’s some of my experiments with non-working code:
void vert (inout appdata_full v, out Input o) {
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
}
void surf (Input IN, inout SurfaceOutput o) {
half4 c = tex2D (_MainTex, IN.uv_MainTex);
o.Albedo = c.rgb;
o.Alpha = c.a;
float3 origin = mul(_Object2World, float4(0.0,0.0,0.0,1.0)).xyz;
float3 cameraDir = mul((float3x3)UNITY_MATRIX_V,float3(0,0,1));
float3 worldPos = mul(UNITY_MATRIX_T_MV, IN.pos);
// HERE IS WHAT I CANNOT FIGURE OUT
// I have tried combining several things such as UNITY_MATRIX_IT_MV and such, to no avail
//o.Alpha = distance(_WorldSpaceCameraPos + cameraDir -IN.pos - origin, float3(0,0,0)) > 240;
//o.Alpha = distance(worldPos, float3(0,0,0)) < 120;
o.Alpha = distance(IN.pos, _WorldSpaceCameraPos) < 240;
o.Albedo = float3(0.5,0.5,0.5);
clip( o.Alpha - 0.5);
o.Albedo.r = IN.normal.x + _Object2World;
o.Albedo.g = IN.normal.y+sin(IN.normal.z);
o.Albedo.b = 1-distance(IN.pos.xyz, _WorldSpaceCameraPos)/240;
}
From what I understand, I would have to revert the projection or view matrix, but I don’t understand how to do that.
Thanks in advance!
Answer by Madeck · Feb 24, 2015 at 08:29 PM
Figured it out. The definition of worldPos is absolute:
struct Input {
float2 uv_MainTex;
// This does the magic
float3 worldPos;
};
void surf (Input IN, inout SurfaceOutput o) {
o.Albedo = IN.worldPos; // this is an absolute position.
}
Your answer
Follow this Question
Related Questions
Fog shader 2 Answers
Absolute Window Position of Unity Application 0 Answers
converting HLSL to GLSL. 0 Answers
How to access the lights properties from within a shader? 1 Answer
Shader error: Shader program of type 'vp' already exists at line .... 1 Answer