Task
Create a pattern of alternating black and red columns, with
9
columns of each color. Then, hide every third column that is colored red.
创建一个黑色和红色交替出现的图案,红黑两种颜色各有9列。并且,每隔3列隐藏一列。
Requirements
The shader should avoid using branching or conditional statements in its code, and instead rely on the
mod
andstep
functions to determine the color of each pixel.
着色器应避免在其代码中使用分支或条件语句,而是依靠mod
和step
函数来确定每个像素的颜色。
Theory
mod
函数用于计算两个数字除法运算的余数。
函数
float mod(float x, float y);
该mod
函数有两个参数:
- •被除数:被除数
- •除数:被除数除以的数。
该函数返回除法运算的余数。
与模运算符的比较
该mod
函数的工作原理与许多编程语言中的模运算符 ( %
) 类似。但是,在处理负数的方式上存在一些差异。在 GLSL 中,该mod
函数始终返回非负结果。
示例
正数的基本用法:
scss
float result = mod(10.0, 3.0); // Result will be 1.0 (10 / 3 has a remainder of 1)
处理负数:
scss
float result = mod(-10.0, 3.0); // Result will be 2.0 (-10 / 3 has a remainder of 2)
实际应用
-
创建重复图案: 通过使用 mod 功能,您可以创建无缝、重复的纹理或图案。
-
动画: 可以通过将值包装在一定范围内来实现循环动画。
-
网格系统: 用于创建基于网格的效果或将屏幕划分为多个部分。
Answer
glsl
uniform vec2 iResolution;
void main() {
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = gl_FragCoord.xy / iResolution.xy;
uv *= 9.0;
float x = fract(uv.x);
float hide = 1.0;
hide = step(1.0, mod(uv.x + 1.0, 3.0)) ;
x = step(0.5, x * hide);
gl_FragColor = vec4(x, 0.0, 0.0, 1.0);
}
效果

练习
最后
如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!