射线和平面求交

射线和平面求交

1、平面方程

如果已知平面的高度(即沿法向量方向的距离)为 height,平面方程可以表示为:

n ^ ⋅ p = h e i g h t \bold{\hat{n}} \cdot p = height n^⋅p=height

p p p 是平面上的任意一点

height 的正负取决于法向量的方向。

2、射线参数方程

r ( t ) = p 0 + t ⋅ d i r \bold{r}(t) = p_0 + t \cdot \bold{dir} r(t)=p0+t⋅dir

p 0 p_0 p0: 是射线的起点
d i r dir dir: 是射线的方向向量
t t t: 表示沿着方向向量走的距离

3、计算交点

n ^ ⋅ ( p 0 + t ⋅ d i r ) = h e i g h t \bold{\hat{n}} \cdot (p_0 + t \cdot \bold{dir}) = height n^⋅(p0+t⋅dir)=height

展开后:
n ^ ⋅ p 0 + t ⋅ ( n ^ ⋅ d i r ) = h e i g h t \bold{\hat{n}} \cdot p_0 + t \cdot (\bold{\hat{n}} \cdot \bold{dir}) = height n^⋅p0+t⋅(n^⋅dir)=height

解这个方程,求出 t t t:
t = h e i g h t − n ^ ⋅ p 0 n ^ ⋅ d i r t = \frac{height - \bold{\hat{n}} \cdot p_0}{\bold{\hat{n}} \cdot \bold{dir}} t=n^⋅dirheight−n^⋅p0

4、代码实现
js 复制代码
/**
 * 计算射线和平面的交点
 * @param source 射线起点
 * @param dir 射线方向
 * @param normal  平面法向量
 * @param height  平面高度
 */
vec3 interceptPlane(in vec3 source, in vec3 dir, in vec3 normal, float height)
{
    float distance = (-height - dot(normal, source)) / dot(normal, dir);

    if (distance > 0.0)
        return source + dir * distance;
    else
        return vec3(infinity);  // 返回一个表示无穷远的向量
}
相关推荐
立志成为大牛的小牛7 分钟前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光9 分钟前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
StarPrayers.2 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫2 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式
235162 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
weixin_307779133 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
柳安忆3 小时前
【论文阅读】Sparks of Science
算法
web安全工具库4 小时前
从课堂笔记到实践:深入理解Linux C函数库的奥秘
java·数据库·算法
爱编程的鱼5 小时前
C# 变量详解:从基础概念到高级应用
java·算法·c#
HalvmånEver5 小时前
红黑树实现与原理剖析(上篇):核心规则与插入平衡逻辑
数据结构·c++·学习·算法·红黑树