Task
Create a shader program that divides the normalized coordinate range of
[0, 1]into10equal intervals across the entire width of the texture. Each interval should be0.1of the total screen width. The left half of each interval should be black, and the right half should be red. As a result, the program should produce a sequence of alternating black and red intervals across the entire width of the texture.
创建一个着色器程序,采用
[0,1]之间的标准化设备坐标,分成10等分,每份的宽度大小相等,都是0.1的宽度,每份的都是左边一半是黑色,右边是红色,一直这样交替出现。
Requirements
The shader should avoid using branching or conditional statements in its code, and instead rely on the fract and step functions to determine the color of each pixel.
着色器应避免在其代码中使用分支或条件语句,而是依靠
fract和step函数来确定每个像素的颜色。
Theory
fract函数用来处理浮点数的小数部分。该函数接受一个参数,可以是float、vec2、vec3或vec4, 并返回[0, 1]之间的值。
示例用法
float x = 3.75;
float fractionalPart = fract(x); // will be 0.75
vec2 v = vec2(1.25, 2.75);
vec2 fractionalParts = fract(v); // will be vec2(0.25, 0.75)
Answer
uniform vec2 iResolution;
void main() {
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = fract(uv.x * 10.0); // 主要是判断小数的第二位【0-1】
gl_FragColor = vec4(step(0.5, x), 0.0, 0.0, 1.0);
}
效果
练习
最后
如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!