Atan--着色器中的角度计算

Task

Create a gradient that transitions from red to green. The weight of each pixel should be determined by the angle between the center-to-pixel ray and the x-axis. Limit the gradient to a circular area with a diameter equal to the height of the texture.
创建一个从红色到绿色的渐变。每个像素的权重应该由从中心到像素的射线与x轴之间的角度来确定。将渐变限制在直径等于纹理高度的圆形区域内。

Theory

函数介绍

atan(y_over_x) :接受一个浮点数,即 y 坐标除以 x 坐标的比值

它的返回值被限制在 [-π/2, π/2](-90° 到 90°)的范围内

atan(y, x): 接受两个参数

atan(y, x) 能够准确判断出点所在的象限,并返回一个覆盖 [-π, π](-180° 到 180°)完整圆周的角度(以弧度为单位)

任务解析

坐标中心化

ini 复制代码
//坐标中心化
uv -= 0.5;

计算角度

scss 复制代码
float angle = atan(uv.y, uv.x); // angle 范围[-π, π]

把弧度转换到0-1

scss 复制代码
float angle = abs(angle / 3.14); // angle [-π, π] / π

限制范围半径为0.5的圆

scss 复制代码
float dist = length(uv);
float color = step(0.5, dist);

Answer

glsl 复制代码
uniform vec2 iResolution;

#define PI 3.14159265359

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  //坐标中心化
  uv -= 0.5;
  
  vec2 ratio = vec2(iResolution.x / iResolution.y, 1.0);
  uv *= ratio;

  float angle = atan(uv.y, uv.x) ; 
  float normalized_angle = abs(angle / PI);

  vec3 color1 = vec3(1.0, 0.0, 0.0);
  vec3 color2 = vec3(0.0, 1.0, 0.0);
 
  vec3 color = mix(color1, color2, normalized_angle);
  float dist = length(uv);
  color -= step(0.5, dist);

  gl_FragColor = vec4(color, 1.0);
}

效果

练习

Atan

最后

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

相关推荐
刘较瘦_17 分钟前
AI 开发中的 Git Submodule 父子仓库模式:前后端分仓管理与协作实践
前端·github
牧艺30 分钟前
cos-design WeatherBackground:用 Canvas 做一个「会变天」的背景引擎
前端·canvas·视觉设计
OpenTiny社区35 分钟前
深度解析 LSP 如何为 AI 装上“眼睛”
前端·ai编程
布列瑟农的星空43 分钟前
流程类SVG画布的通用开发范式
前端
fsssb1 小时前
Chromium 源码学习笔记(七):那些跨进程的调用,底下都是同一个东西——Mojo
前端
MichaelJohn1 小时前
从零星白屏到“启发式缓存”,记录一次刚接手屎山的惊险排查
前端
程序员黑豆2 小时前
鸿蒙应用开发:6种图片加载方式详解
前端·华为·harmonyos
半个落月2 小时前
用 React 搭一个 WebGPU 模型加载页:从状态驱动到可复用进度条
前端·react.js
雪隐2 小时前
个人电脑玩AI-13让5060 Ti给你打工——我用 0.9B 小模型终结了"谁来记会议纪要"这个世纪难题
前端·人工智能·后端
橘子星2 小时前
我一个前端切图仔,凭什么能在浏览器里跑大模型?
前端·javascript·前端框架