Search Unity

Pivot world position.

Discussion in 'Shaders' started by Phantom_X, Jun 15, 2017.

  1. Phantom_X

    Phantom_X

    Joined:
    Jul 11, 2013
    Posts:
    314
    Hey,
    I'm using this macro to get some type of fog on objects.
    Code (CSharp):
    1.                
    2. inline float DistanceFromCamera2 (float4 vert, float zPos, float minDst, float maxDst)
    3.                
    4. {
    5.        half3 obj2w     = mul((half4x4)unity_ObjectToWorld, vert);
    6.        half3 viewDirW  = min(0,half3(obj2w.xy,zPos) - obj2w);
    7.  
    8.        return saturate((length(viewDirW) - minDst) / (maxDst - minDst));
    9.  }
    10.  
    The paremeter zPos is set by a script. It's basically transform.position.z
    Thing is I need to update this every frame if I want the gradient to stay the same if the object moves.

    Is there a way to compute this value in the shader?

    Thanks!
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    float3 objectWorldPosition = unity_ObjectToWorld._m03_m13_m23;
     
  3. Phantom_X

    Phantom_X

    Joined:
    Jul 11, 2013
    Posts:
    314
    Cool!! I did't know that this existed! Big thanks!
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    Note that this won't work if the object gets statically or dynamically batched! The position you'll get will always be 0, 0, 0 for batched geometry. You'll need to disable batching in your project or on that shader for that to work.
     
  5. Phantom_X

    Phantom_X

    Joined:
    Jul 11, 2013
    Posts:
    314
    Last edited: Jun 16, 2017
  6. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    It is not documented anywhere explicitly, mainly because it's just a property of transform matrices and not anything unique to Unity. The documentation stating that there is an "Object to World" transform is enough to know that information exists if you are familiar with matrix transforms, though to be fair most people starting out on shaders don't really understand matrix transforms, and Unity's documentation still lists the obsolete _Object2World that was removed over a year ago.

    Also dynamic batching works on dynamic, aka moving, objects, hence the name. So there fact your objects move doesn't prevent batching.
     
    WayneJP and boboisgood like this.