Task
Draw an image with
5
sinusoidal waves coming out from the center of the screen. The waves should be based on the distance from each pixel to the center. Adjust the sine values to a range from0
to1
, and use these values to control the brightness of the red color. This will create a repeating pattern of peaks and troughs of the waves. Use3.14
as the approximate value for π.
绘制一幅图像,其中有5个正弦波从屏幕中心向外扩散。波形应基于每个像素点到中心的距离。将正弦值调整到0到1的范围内,并用这些值来控制红色的亮度。
Theory
函数介绍
sin(x)
: 正弦函数,*输入一个线性增长的值,输出一个在[-1, 1]
区间内平滑振荡的值
任务拆解
1. 实现一个完整的圆周
- 在弧度制中,一个完整的圆周 是
2 * π
,正弦函数sin(x)
的一个完整周期恰好对应一个完整的圆周 uv.x
的值从屏幕的左边缘 (0.0) 线性增长到右边缘 (1.0) ,对应sin(x)
的[0, 1]
也就是弧度的[0,π]
,正好是半圆。因此完整的圆为sin(x * 2.0 * π)
- 而颜色的范围也在
[0,1]
之间,所以需要把sin(x)
的[-1, 1]
转换到[0, 1]
之间
ini
// 最终的一个完整圆的代码为
float wave = sin(uv.x * 2.0 * PI);
float normalized_wave = wave * 0.5 + 0.5;
2. 增加频率
- 增加频率也就意味着
sin(x)
出现了多个圆,可以通过控制x
的变化来实现
ini
float frequency = 10.0;
float wave = sin((uv.x * 2.0 * PI) * frequency );
3.实现圆控制
- 使用
length
或者distance
来控制圆的绘制
Answer
glsl
uniform vec2 iResolution;
#define PI 3.14
void main() {
vec2 uv = gl_FragCoord.xy / iResolution.xy;
vec2 ratio = vec2(iResolution.x / iResolution.y, 1.0);
uv -= 0.5;
uv *= ratio;
float wave = sin(length(uv) * 2.0 * PI * 5.0 );
float normalized_wave = wave * 0.5 + 0.5;
gl_FragColor = vec4(vec3(normalized_wave, 0, 0), 1.0);
}
效果

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