Tutorial : How to make a simple stripe pattern.
Each point in the plane has coordinate. Attempting to create a shader effect is basically visualizing 2D math onto the plane. Here let me introduce a simple example.
//This shader will visualize coordinates
vec2 uv = gl_FragCoord.xy / iResolution.xy;
gl_FragColor = vec4(uv.x,uv.y,0,1);
The color red will represent x coordinate and the green hue will represent y coordinate.
insert picture
For now, we want to create simplest shader effect; a stripe. We won't need uv.y value for this tutorial.
vec2 uv = gl_FragCoord.xy / iResolution.xy;
gl_FragColor = vec4(uv.x,0,0,1);
insert picture
You can see that red hue gets intense as it directs to the right side. That's because x value of the coordinate gets higher as you move to the right side; the left end x coordinate starts from 0 and the right end x coordinate is 1.
Since we have this basic understanding let's try something "intuitive"
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float color = 0.0;
if(uv.x < .5 ) color= 1.0 ;
gl_FragColor = vec4(color,0,0,1);
There you have a stripe pattern. Wait... that doesn't look quite right. Yes this is just red and black. Stripe pattern is consist of more than just two color sections.
There...!
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float color = 0.0;
if(uv.x < .2 ||(uv.x >.4 && uv.x < .6) || (uv.x > .8 && uv.x <1.0 )) color= 1.0 ;
gl_FragColor = vec4(color,0,0,1);
but what if we want to make N number of stripe?
What I am attempting to display is that if you try to approach shader programming with more of traditional programming "logic" then you are likely to fail. When it comes to shader, it's all about math.
Speaking of math, what's the pattern that most resemble "stripe" pattern? In other words, what's the equation that looks like stripe? Yes. Y = sin(X). However our X value range from 0.0~1.0 If we want to use Y = sin(X) we want our x value to range from 0.0 ~ 6.28(which is roughly 2 PI)
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = uv.x * 2.0 *PI;
float y = sin(x);
gl_FragColor = vec4(y,0,0,1);
We now have "stripe" in terms of pattern generated by an equation. Why should we take this approach? Not only can this be faster but also it eliminates need of writing ugly if conditions to have N number of stripe. If we wanted to have more than one stripe, we could simple extend the pattern by increasing the maximum X value further.
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = uv.x * (2.0 *PI * 10.0); //ta dan!
float y = sin(x);
gl_FragColor = vec4(y,0,0,1);
You might say this shader doesn't produce the perfect stripe like from early shader, but really, all you need to do is write more fitting equation!
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = uv.x * (2.0 *PI * 10.0);
float y = sin(x) / abs(sin(x) );
gl_FragColor = vec4(y,0,0,1);
Weeee~~~
Next : How to make a wavy stripe pattern.