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更轻松!!

相关推荐
攀登的牵牛花1 分钟前
2.1w Star 的 pretext 火在哪?
前端·github
散步去海边9 分钟前
Pretext 初识——零 DOM 测量的文本布局引擎
前端
xw-busy-code12 分钟前
npm 包管理笔记整理
前端·笔记·npm
踩着两条虫24 分钟前
AI驱动的Vue3应用开发平台 深入探究(十六):扩展与定制之自定义组件与设计器面板
前端·vue.js·人工智能·开源·ai编程
棋鬼王30 分钟前
Cesium(十) 动态修改白模颜色、白模渐变色、白模光圈特效、白模动态扫描光效、白模着色器
前端·javascript·vue.js·智慧城市·数字孪生·cesium
酉鬼女又兒33 分钟前
零基础快速入门前端蓝桥杯Web备考:BOM与定时器核心知识点详解(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·职场和发展·蓝桥杯
ThridTianFuStreet小貂蝉34 分钟前
面试题1:请系统讲讲 Vue2 与 Vue3 的核心差异(响应式、API 设计、性能与编译器)。
前端·javascript·vue.js
俊劫38 分钟前
AI Harness - 2026 AI 工程新范式
前端·openai·ai编程
前端付豪1 小时前
Prompt Playground(实现提示词工作台)
前端·人工智能·后端
竹林8181 小时前
在NFT项目中集成IPFS:从Pinata上传到前端展示的完整实战与踩坑
前端·javascript