三个JS检测多个运动物体碰撞
Three JS detect multiple moving object collision
我目前有多个对象,每个对象都像这样随机向前移动
model.lookAt(position_x, 0, position_z);
setInterval(function(){
model.translateZ(0.015);
}, 10);
我需要每个物体在向前移动时避免相互碰撞。我发现此解决方案建议使用边界框进行碰撞检测,但它似乎仅适用于两个对象之间的碰撞:
是否可以有多个对象,每个对象都有自己的碰撞检测?
谢谢!
你可以这样做:
var objectA = ...your first object...
var objectB = ...your second object...
var objectC = ...your first object...
var objectD = ...your second object...
firstBB = new THREE.Box3().setFromObject(objectA);
secondBB = new THREE.Box3().setFromObject(objectB);
thirdBB = new THREE.Box3().setFromObject(objectC);
fourthBB = new THREE.Box3().setFromObject(objectD);
const BBs = [firstBB, secondBB, thirdBB, fourthBB];
// at each frame, you could do this to check if some objects are colliding :
BBs.forEach(bb => {
// Filter out this bb from BBs
const otherBBs = BBs.filter(other => other !== bb)
// Check if any of the other BBs intersects with this bb
otherBBs.forEach(other => {
if (bb.intersectsBox(other)) {
// Collision ! Do something
}
})
})
我目前有多个对象,每个对象都像这样随机向前移动
model.lookAt(position_x, 0, position_z);
setInterval(function(){
model.translateZ(0.015);
}, 10);
我需要每个物体在向前移动时避免相互碰撞。我发现此解决方案建议使用边界框进行碰撞检测,但它似乎仅适用于两个对象之间的碰撞:
是否可以有多个对象,每个对象都有自己的碰撞检测?
谢谢!
你可以这样做:
var objectA = ...your first object...
var objectB = ...your second object...
var objectC = ...your first object...
var objectD = ...your second object...
firstBB = new THREE.Box3().setFromObject(objectA);
secondBB = new THREE.Box3().setFromObject(objectB);
thirdBB = new THREE.Box3().setFromObject(objectC);
fourthBB = new THREE.Box3().setFromObject(objectD);
const BBs = [firstBB, secondBB, thirdBB, fourthBB];
// at each frame, you could do this to check if some objects are colliding :
BBs.forEach(bb => {
// Filter out this bb from BBs
const otherBBs = BBs.filter(other => other !== bb)
// Check if any of the other BBs intersects with this bb
otherBBs.forEach(other => {
if (bb.intersectsBox(other)) {
// Collision ! Do something
}
})
})