【发布时间】:2012-12-18 03:27:42
【问题描述】:
我正在用 javascript 制作游戏,但我找不到任何类似函数的东西,它需要 2 个边界框对象并在它们相交时返回 true。我发现的所有示例对于我的小游戏来说似乎都太复杂了,而且大多数都是特定于语言的:/
//my box object
function bounding_box (x, y, width, height, rotation) {
var box = {};
box.x = x;
box.y = y;
box.w = width
box.h = height;
box.r = rotation; //degrees from origin - all objects in the game have the same rotation origin
return box;
}
function boxes_collide (a, b) {
//if collision return true
//else return false
//my box collision function at the moment
//doesn't work with rotation
return !(
((a.y + a.h) < (b.y)) ||
(a.y > (b.z + b.h)) ||
((a.x + a.w) < b.x) ||
(a.x > (b.x + b.h))
);
}
//create boxes
var boxa = bounding_box(0, 0, 5, 3, 45);
var boxb = bounding_box(1, 3, 4, 2, 90);
//test for collision
if (boxes_collide (boxa, boxb)) {
alert('collision');
}
我在这个小问题上被困了几个小时,任何帮助将不胜感激! :)
【问题讨论】:
-
我已经有了几乎完全一样的功能,但是当我的盒子旋转时,它不是很准确:/
-
您应该对定向边界框(旋转矩形)使用分离轴测试。不久前我写了一个小 SAT 可视化来帮助我理解 OBB 和 SAT。这是 JSBin,告诉我这是不是你需要的:jsbin.com/esubuw/4
-
希望我的answer 也能帮到你。
标签: javascript collision-detection