In the previous post the cube with a block spot was fixed so it is time to explain how the effect of color change is achieved.
Let’s see again the fragment shader and focus on the abs(...) part of line 9
1#version 330
2
3out vec4 outColor;
4in vec3 posObj;
5uniform float uTime;
6uniform float uTimeFreq;
7
8void main() {
9 outColor = vec4(posObj * abs(sin(uTime * uTimeFreq)), 1);
10}The params uTime is a value passed from SHADERed and its value is the elapsed time since the application has been started. uTimeFreq is the user defined variable with a value that influences how fast the objects fades.
The core of the fading effect is given by the periodic function sin.
The image below shows a graph of the sine function with domain values between [-2π,2π].
Moreover, no matter which value is passed to the function, the result is always a number between -1 and 1 : this is not entirely true when the function is computed using floating point values, but this is another story and let’s pretend that the previous assertion is true (for more information see here)
This is particularly handy when we want to animate a value between 0 and 1 in a “ping-pong” fashion. However, as previously said, the results are between -1 and 1. To “move” them in the positive range 0-1 there are two ways :
The choice in the shader was to use $abs(sin(x))$ : the animation below shows the values assumed by the function. As you can see it goes from 0 to 1, then it reverses the direction and when it reaches 0 again it repeats.
The last parameter to explain is uTimeFreq : it represents the frequency, that is the inverse of the period.
Incresing the value of uTimeFreq speeds up the fading effect.
The following graph shows the function $sin(4 \cdot x)$