射线和平面求交

射线和平面求交

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);  // 返回一个表示无穷远的向量
}
相关推荐
土司大王12 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
大熊背13 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander25814 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
祖力5514 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜14 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者14 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
_Narcissus_15 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.15 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks15 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路16 小时前
算法8.环形队列
算法