Search Unity

Color based on height

Discussion in 'Shaders' started by RiokuTheSlayer, Mar 5, 2015.

  1. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    Hey, all. Shader noob here. I have a quick question.

    I'd like a shader that has 5 arguments. A texture, a "low tint" color, and a "high tint" color, and a value for the low and high limits of the tint.

    Then, I want to have the shader use the material as normal, with normal lighting and shadows, but I want it to change color based on the world Y position. The closer it is to the "upper limit" value in y position, the closer the color tint is to the high tint color. The closer to the "lower limit" value, the closer the tint will be to the "Low tint" color.

    I know shaders are able to get the world position, but I myself have never scripted shaders, and I don't know how you would specify the colors and apply them to the object based on the height.

    If anyone could throw me a shader that has this, and/or shoot me a tutorial on shaders, it'd be greatly appreciated.

    Thanks in advance -Rio
     
  2. alti

    alti

    Joined:
    Jan 8, 2014
    Posts:
    94
    in shadergraph use absolute world "position" node.

    connect to split. A split node gives you the channels within a variable. In this case RGB stands for XYZ.

    apply G from split to subtract node since you want the world height, and then make a "float" variable for the b slot of the subtract node to offset the Y limit. This "offsetY" variable will drag your entire calculation up or down. Very handy!

    Now lets control the gradient:
    Make a "float" variable for the height, and another "float" variable for the spread (how sharp the gradient is), and plug those in to a multiply node. optionally you can clamp this result to ensure you're not about to divide by zero...

    Connect the subtract and multiply nodes into a divide node, where subtract goes into the A slot.
    Personally, I'd clamp the result between 0 and 1, this way the results arent too intense / funky.

    Plug all that out of the clamp into a lerp node in the T slot. Then fix the A and B slots with your two colors.
    Use the exposed variables listed above (if they aren't properties already, make them properties) to tweak the position of your color, spread, and offset.

    I'm no expert but that should do the trick. For more info, I'd check out this guy's video:


    He does some things slightly different, but the principles are the same.