Search Unity

_Object2World issue to get object center

Discussion in 'Shaders' started by Ellenack, Feb 10, 2016.

  1. Ellenack

    Ellenack

    Joined:
    Feb 16, 2014
    Posts:
    41
    Hi !

    I am currently having a small issue with a shader I am working on. The idea is pretty simple : make the vegetation move depending on the distance between the vertex and the center of the object. At first, I thought it would be really simple :

    Code (CSharp):
    1. void vert (inout appdata_full v)
    2. {
    3.     float dist = length( v.vertex.xyz ); // here it is, the distance to the center of the object !
    4. }
    But... nope, noppity noopy nope, it isn't working. I tried many things, like this :

    Code (CSharp):
    1. void vert (inout appData i, out Input o)
    2. {
    3.     UNITY_INITIALIZE_OUTPUT(Input,o);
    4.  
    5.     float3 wPos = mul(_Object2World, i.vertex).xyz;
    6.     float3 center = mul( _Object2World, float4( 0, 0, 0, 1 ) ).xyz;
    7.    // tried _Object2World[3],or float3(_Object2World[0].w, _Object2World[1].w, _Object2World[2].w ) as a desesperate mesure, but still, no luck.
    8.  
    9.     o.col = distance( center, wPos ); // Just to display the color and having an idea of the distance as a debug
    10. }
    Saying it isn't working is pushing it though. In fact, it's working when it wants too. Here is a little screenshot of it working and not working side by side :

    leeeeeel.png

    The issue appear just by moving the camera. And I have no idea why it affects some objects and not the others. Am I missing something ?

    Thanks for any help. :)

    PS : I joined the shader I use as a Debug, it's perfectly showing my issue.
     

    Attached Files:

  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Do you have multiple trees and batching turned on? Batching, both static and dynamic, generates a new mesh that is a combination of multiple meshes, so the "center" might not be where you think anymore.

    It's best to store distance to the center of a mesh in either the mesh's vertex colors or an additional UV channel. It'll be cheaper too as you avoid needing to do the length() in your shader.
     
  3. Ellenack

    Ellenack

    Joined:
    Feb 16, 2014
    Posts:
    41
    Well, that was probably it. I had no idea that batching modified the object space, but now that I think about it, it's pretty obvious. Well, thanks (again) for your help. :) I decided to bake the length in the red channel of the vertex color, only to find that Unity automatically clamp it between 0 and 1. Shame. I just ended up by dividing the baked length by 10 to solve this last issue. :D