javascript - AABB 分离轴定理,求重叠深度
问题描述
我想检测到 aabb 之间的冲突。我想要重叠量、穿透深度,以便我可以用这些信息将它们分开。
我试图理解下面的代码,在我的情况下它会产生错误的结果:例如:
对于 aabb [ x, y, width, height ], [0, 780, 60, 60] 和 [0, 606, 120, 240] 它会产生 xOverlap 60, yOverlap -23,而不是应该是 yOverlap 6。
/*
* Collision Manifold
* https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6\
331#:~:text=Collision%20resolution%20is%20the%20act,allow%20them%20to%20remain%20intersecting.&text=The%20idea%20behind%20impulse%20res\
olution,to%20separate%20objects%20found%20colliding.
*/
function aabbvsaabb(a, b) {
let normal,
penetration;
let n = [b.pos[0] - a.pos[0], b.pos[1] - a.pos[1]];
let aExtent = a.width / 2,
bExtent = b.width / 2;
let xOverlap, yOverlap;
xOverlap = aExtent + bExtent - Math.abs(n[0]);
xOverlap = Math.min(xOverlap, Math.min(a.width, b.width));
if (xOverlap > 0) {
aExtent = a.height / 2,
bExtent = b.height / 2;
yOverlap = aExtent + bExtent - Math.abs(n[1]);
yOverlap = Math.min(yOverlap, Math.min(a.height, b.height));
if (yOverlap > 0) {
if (xOverlap < yOverlap) {
normal = n[0] < 0 ? [-1, 0]: [1, 0];
penetration = xOverlap;
} else {
normal = n[1] < 0 ? [0, -1]:[0,1];
penetration = yOverlap;
}
}
}
return {
normal,
xOverlap,
yOverlap
};
};
function rect(x, y, w, h) {
return {
x, y, width: w, height: h,
pos: [x, y]
};
}
let manifold = aabbvsaabb(rect(0, 780, 60, 60),
rect(0, 606, 120, 240));
console.log(manifold);
解决方案
推荐阅读
- javascript - 如何将我的链接从 samplesite.com/pages?id=firstList 更改为 samplesite.com/pages/firstList
- kubernetes - 流水线中的通量写入标签
- pygame - pygame 的 display.set_mode 函数中的 SCALED 标志无效
- variables - 邮递员断言两次相同的变量
- python - 比较和乘以列表中的元素
- c# - ASP.Net web api:日志中间件:System.ObjectDisposedException:无法访问已关闭的流
- python - 如何接收带附件的电子邮件
- asp.net - Cache-Control:private 和 no-store 是互斥的吗?
- docker - Hasura 控制台错误:[...] 无法建立连接,因为目标机器主动拒绝它
- html - 包含替代文本的 CSS 伪元素在 IE 中不起作用