- Home /
Shader local space doesn't match object local space?
I have a shader that I'm using to add an alpha cutoff to an object so anything past the given point isn't rendered. For that I'm using
void vert (inout appdata_full v, out Input o) {
UNITY_INITIALIZE_OUTPUT(Input,o);
o.localPos = mul(_World2Object, v.vertex).xyz;
}
void surf (Input IN, inout SurfaceOutputStandard o) {
if (IN.localPos.z > _Cutoff)
{
discard;
}
else
{
fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
}
o.Alpha = _Alpha;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
}
In order to set the _Cutoff parameter, when some object (A) collides with the object (B) that has this shader, I want to get the position of A in B's local space. Then I should just be able to set _Cutoff to the z value. So I get that local position using
Vector3 locPos = B.transform.InverseTransformPoint(A.transform.position);
But as A passes through B, its range of local Z values is completely different than the range of values I used to test the shader so the object goes from invisible to fully visible. Shouldn't these values be in the same coordinate system here? How do I get these 2 local coordinate systems to match up?
Why dont you convert everything to world coordinates and work from there?
Answer by homer_3 · Feb 14, 2017 at 03:59 AM
Using
o.localPos = v.vertex.xyz;
in my vertex shader seemed to get it. I guess the vertex comes into the vertex shader in local coords already?
Answer by tcz8 · Feb 13, 2017 at 07:12 PM
You can convert an object's local coords to match that of another object by converting the first object's coords to worldspace and then back to the object space of the 2nd BUT it may be easier to just convert everything to worldspace and work from there.
Your choice.
This should work:
// Convert object space to world space
float4 NewCoord = mul(_Object2World, CoordToConvert);
// Convert worldspace to object space
float4 NewCoord = mul(_World2Object, CoordToConvert);
See the built in shaderlab varialbes here (including all transform matrix): https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html
Good Luck.
Your answer
Follow this Question
Related Questions
Is it possible to rotate coordinate system instead of object? 1 Answer
Hexagon Grid 1 Answer
Unity is a Left-Handed Coordinate System? Why? 5 Answers
Getting UI into the right position after releasing drag 1 Answer
How to get a vector3 (postion) 1 unit away from another in the direction of a 3rd vector3? 2 Answers