- Home /
SHADER: Get *object* position or distinct value per *object*
Is it possible to get the current Object's 'base' world position in a vertex function?
I was thinking something like this:
float3 baseWorldPos = mul ( _Object2World, float4(0,0,0,0) ).xyz;
...but on testing I'm fairly certain it's returning a zero vector ( because its a multiplication? ).
Otherwise is there another way to get a distinct value per object, so that a shader's effects can be made unique for each individual object?
Thanks.
Answer by mig · Mar 26, 2012 at 02:57 PM
To get the position, you need to transform float4(0,0,0,1).
Am I missing something here? None of this appears to work (Unity 5.2 Deferred Rendering) float timeOffset = length(mul(_Object2World, float4(0,0,0,1)));
Answer by tonyoakden2 · Oct 23, 2017 at 04:21 AM
I think the position is in the last row of the matrix and you can use the HLSL swizzle command to get it directly thus:
float3 baseWorldPos = unity_ObjectToWorld._m30_m31_m32;
Having said that it's quite possible the shader compiler optimizes the whatever the code anyway.
also it might be ObjectToWorld._m03_m13_m23; :)
Answer by defrummel · Aug 27, 2020 at 04:04 PM
float3 baseWorldPos = unity_ObjectToWorld._m03_m13_m23;
Answer by JLJac · Oct 19, 2020 at 08:08 AM
Hi, I'm trying to do this with deferred rendering and have a surprising issue - at certain camera angles the world pos (unity_ObjectToWorld._m03_m13_m_23) jumps to (0,0,0).
This confuses me, because to my understanding ObjectToWorld should be independent of the camera? I don't get why the transformation between object and world space would be affected by the projection matrix at all, to my understanding they should be completely separate.
The issue is not there in forward rendering mode.
If anyone with more insight could help explain that would be much appreciated!
Batching! As soon as 2+ objects are batched, unity_ObjectToWorld._m03_m13_m_23 becomes 0,0,0 (rather than say a point between the batched objects). Moving the camera can change the batches.