Vector Normaliztion -- 向量归一化

Task

Write a shader program that divides the screen into two equal parts. The origin of the left part is at (0.25, 0.5), and the origin of the right part is at (0.75, 0.5). In the left part, display the cosine of the angle between the positive X-axis and the vector directed from the origin to the current pixel position. In the right part, display the sine of the angle between the positive X-axis and the vector directed from the origin to the current pixel position.
编写一个着色器程序,将屏幕分割成两个相等的部分。左侧部分的原点位于 (0.25, 0.5),右侧部分的原点位于 (0.75, 0.5)。在左侧部分,显示X轴正方向与从原点指向当前像素位置的向量之间夹角的余弦值。在右侧部分,显示X轴正方向与从原点指向当前像素位置的向量之间夹角的正弦值。

Theory

函数介绍

  • normalize(): 向量归一化(Vector Normalization)

它接收一个向量,然后返回一个指向相同方向,但长度恰好为 1 的单位向量(Unit Vector)
常常用于光照计算,方向相关内容

点积介绍

两个单位向量进行点积运算时,其结果等于它们之间夹角的余弦值(cosine)

  • dot(A, B) = 1:方向完全相同。
  • dot(A, B) = 0:方向互相垂直。
  • dot(A, B) = -1:方向完全相反。

Answer

glsl 复制代码
uniform vec2 iResolution;

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;

  //左边,和方向有关时需要向量归一化
  vec2 left = normalize(uv - vec2(0.25, 0.5));
  // 右边
  vec2 right = normalize(uv - vec2(0.75, 0.5));
  
  float condition = step(0.5, uv.x);
  // 因为是单位向量,所有cos = left.x
  float t = (1.0 - condition) * left.x + condition * right.y ;
  
  gl_FragColor = vec4(vec3(t), 1.0);
}

效果

练习

Vector Normaliztion

最后

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

相关推荐
知花实央l1 天前
【Web应用实战】 文件上传漏洞实战:Low/Medium/High三级绕过(一句话木马拿webshell全流程)
前端·学习·网络安全·安全架构
华仔啊1 天前
JavaScript + Web Audio API 打造炫酷音乐可视化效果,让你的网页跟随音乐跳起来
前端·javascript
鸡吃丸子1 天前
SEO入门
前端
檀越剑指大厂1 天前
【Nginx系列】Tengine:基于 Nginx 的高性能 Web 服务器与反向代理服务器
服务器·前端·nginx
是你的小橘呀1 天前
深入理解 JavaScript 预编译:从原理到实践
前端·javascript
uhakadotcom1 天前
在使用cloudflare workers时,假如有几十个请求,如何去控制并发?
前端·面试·架构
风止何安啊1 天前
栈与堆的精妙舞剧:JavaScript 数据类型深度解析
前端·javascript
用户47949283569151 天前
Chrome DevTools MCP:让 AI 助手直接操作浏览器开发工具
前端·javascript·chrome
Rysxt_1 天前
Vuex 教程 从入门到实践
前端·javascript·vue.js
by__csdn1 天前
Node.js版本与npm版本的对应关系
前端·npm·node.js