Smoothstep

Task

Create a gradient effect that smoothly transitions from red to green. The color change should be most noticeable between the x-coordinates of 0.25 and 0.75.
创建一个从红色平滑过渡到绿色的渐变效果。颜色变化设置为x坐标的 0.25 和 0.75 的 x 之间

Requirements

The shader should avoid using branching or conditional statements in its code, and instead rely on the smoothstep and mix functions to determine the color of each pixel.
着色器应避免在其代码中使用分支或条件语句,而是依赖 Smoothstepmix函数来确定每个像素的颜色。

Theory

smoothstep函数基于第三个线性插值因子在两个值之间进行平滑插值。该函数通过在插值过程中应用平滑曲线,提供了比线性插值更为平滑的过渡。

函数

ini 复制代码
smoothInterpolation = smoothstep(edge0, edge1, x)

smoothstep函数有三个参数:

  • edge0: 下限阈值
  • edge1 : 上限阈值
  • x : 插值因子

插值因子说明

  1. 如果 x 小于或等于 edge0, 结果为 0。

  2. 如果 x 大于或等于 edge1, 结果为 1。

  3. 如果 x 介于 edge0edge1 之间,则使用埃尔米特特插值函数在 0 和 1 之间平滑插值。

示例代码

scss 复制代码
// result will be a smooth color interpolation between red and blue
vec3 out = mix(color1, color2, smoothstep(0.2, 0.8, factor));

在这个例子中,输出颜色值根据因子值从 0.2 平滑地过渡到 0.8:

  • 当因子小于 0.2 时:smoothstep 函数的值为 0.0, 导致输出更接近 color1。
  • 当 factor 大于 0.8 时:smoothstep 函数求值为 1.0, 导致输出更接近 color2。
  • 当 factor 介于 0.2 和 0.8 之间时:转换是平滑连续的,为混合发生的位置提供了更多的控制。

Answer

glsl 复制代码
uniform vec2 iResolution;

void main() {
  // Normalized pixel coordinates (from 0 to 1)
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  vec3 redColor = vec3(1.0, 0.0, 0.0);
  vec3 greenColor = vec3(0.0, 1.0, 0.0);
  vec3 outColor = mix(redColor, greenColor, smoothstep(0.25, 0.75, uv.x));
  gl_FragColor = vec4(outColor, 1.0);
}

效果

练习

Smoothstep

最后

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

相关推荐
烛阴12 分钟前
解锁 TypeScript 的元编程魔法:从 `extends` 到 `infer` 的条件类型之旅
前端·javascript·typescript
前端开发爱好者37 分钟前
弃用 ESLint + Prettier!快 35 倍的 AI 格式化神器!
前端·javascript·vue.js
vivi_and_qiao1 小时前
HTML的form表单
java·前端·html
骑驴看星星a2 小时前
Vue中的scoped属性
前端·javascript·vue.js
四月_h2 小时前
在 Vue 3 + TypeScript 项目中实现主题切换功能
前端·vue.js·typescript
qq_427506082 小时前
vue3写一个简单的时间轴组件
前端·javascript·vue.js
雨枪幻。3 小时前
spring boot开发:一些基础知识
开发语言·前端·javascript
lecepin3 小时前
AI Coding 资讯 2025.8.27
前端·ai编程
TimelessHaze4 小时前
拆解字节面试题:async/await 到底是什么?底层实现 + 最佳实践全解析
前端·javascript·trae
执键行天涯4 小时前
从双重检查锁定的设计意图、锁的作用、第一次检查提升性能的原理三个角度,详细拆解单例模式的逻辑
java·前端·github