I am attempting to set something to be a different colour depending on the height it is.

For example, if the height is between 0 and 80, I would like black to equal 1. If it is between 80 and 120, I would red to equal 1, if it's between 120 and 200 I would like to be green, and if it's between 200 and 255 I would like to be blue.

All four variables need to add up to "1" every time, or else everything will go wrong.

In itself, it would be easy:

if (height < 80) black = 1;

However, the problem is, I would like there to be a smooth transition.

For example, if the height equals 70, I would like black to be 0.7, and red to be 0.3, and all the other numbers remain as 0. If it was 80, I would like both numbers to equal 0.5, and if it was 90, I would like red to be 0.7 and black to be 0.3.

How could I do this with the least possible calculations? I will be implementing this on the graphics card, so a method with the least possible calculations would be very much appreciated (since I will have to run this code every time a pixel is drawn on the screen).


1 Answer 1


Degree 3 "spline" polynomials. Basically, $3t^2-2t^3$, with $t$ retargeted to the numbers of your case. Especially when programming on a graphics card, in glsl you have smoothstep doing exactly that: see derivations, figures and API in https://en.wikipedia.org/wiki/Smoothstep

  • $\begingroup$ I'm slightly confused here, probably because my mathematical notation isn't really the best. Could you perhaps explain what I actually need to do to get the result? $\endgroup$ Nov 2, 2015 at 12:48
  • $\begingroup$ something like red = smoothstep(50,80,h)*smoothstep(150,120,h), and same for green and blue. just try here: shadertoy.com/new $\endgroup$ Nov 2, 2015 at 13:00
  • $\begingroup$ Now, it also depends the kind of color interpolation you want in transitions: RGB or HLS ? (i.e. like fading R,G,B light spots, ordre like traveling in rainbow colors) $\endgroup$ Nov 2, 2015 at 13:01
  • $\begingroup$ That "ShaderToy" site doesn't seem to recognize smoothstep() as a method. The point is, I still don't know what these methods do nor how I would use them, nor what mathematical solution I would want/need. Could you perhaps update your answer to be more informative about that? $\endgroup$ Nov 2, 2015 at 13:14
  • 1
    $\begingroup$ Man, I gave you the wikipedia link with math formula, pseudo code, figure, and explanations. Plus an example. Have you read them ? $\endgroup$ Nov 2, 2015 at 13:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .