Search Unity

Question Flat gradient worldspace shader

Discussion in 'Shader Graph' started by SlayerDRIZZT, Sep 18, 2020.

  1. SlayerDRIZZT

    SlayerDRIZZT

    Joined:
    Feb 22, 2019
    Posts:
    5
    Hi everyone,

    I would want to have a shader that allow me to have a custom gradient (texture or color) from the base to top of a object (or better, group object).
    This gradient needs to be flat whatever the position is the camera view... (see screenshot to understand ^^')

    If I use a worldspace position node, it works only if I look it from horizontal view.
    But if I use a viewspace position node, it works but the gradient doesn't start from the base to the top of the object but of my screen (normal ^^')

    Idea will be to flat my object like a photoshop layer and then to applicate a worldspace position node but, I don't know how to do and I really need your help.

    I'm with URP with only unlit shader. (3D game with 2D rendering, no shadow)

    Thx and sorry for my language XD
     

    Attached Files:

  2. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,493
    Your problem is perspective, also probably object space is a better space?
    You probably should flatten the mesh by scalling by the "1-dot product + thickness offset" of the camera vector
     
  3. SlayerDRIZZT

    SlayerDRIZZT

    Joined:
    Feb 22, 2019
    Posts:
    5
    Hi Neoshaman !

    Thx to your reply.
    I understand the idea to flat the mesh but not the way to do it.
    Can you make an exemple ?
     
  4. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,493
    Basically what you want is to scale the mesh so that it's almost flat (and conserved the 3D slihouette), but not flat enough that it start having visual artefact:
    - the easiest way to do it is to scale along the object axis, but then it wouldn't be dependent on the view, you want to scale along the view, but how do you know which vertices to flatten and in which direction?
    - a dot product of two NORMALIZED vector return how much they are aligned or not, ie 1 if they are in teh exact same direction to 0 if they are perpendicular and then -1 if they are in opposite direction.
    - therefore you want to find all vertices that are oriented in the direction (parallel) of the view vector and alter their position so that they scale down in that direction (ie are close to either 1 or -1), those who are perpendicular to view would remain the same.
    - if you add the view direction to the mesh point, the mesh will be a bit further in the direction of the view vector, so what you want is take advantage of that to move the point but scale by the dot product so that they flatten, vector with zero dot product won't moved by the scale view (position + view * 0 * scale) vector, vector with non zero dot product will move by the percent defined by the dotproduct, and vector at 1 will have the full offset.