I recently came across a tutorial on MDN that discussed the intersection of bounding boxes. Intrigued, I decided to try out the code snippet provided:
const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
const testBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
testBox = new THREE.Mesh(testBoxGeometry, testBoxMaterial);
testBox.geometry.computeBoundingBox();
testBoundingBox = new THREE.Box3(
testBox.geometry.boundingBox.min,
testBox.geometry.boundingBox.max
);
testBox.position.set(5, 0, 5);
scene.add(testBox);
const cameraBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
const cameraBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
cameraBox = new THREE.Mesh(cameraBoxGeometry, cameraBoxMaterial);
cameraBox.geometry.computeBoundingBox();
cameraBoundingBox = new THREE.Box3(
cameraBox.geometry.boundingBox.min,
cameraBox.geometry.boundingBox.max
);
scene.add(cameraBox);
However, when I tested for intersection in my animate function:
if (testBoundingBox.intersectsBox(cameraBoundingBox)) {
console.log(`intersection`);
}
I encountered an issue where the green boxes appeared not to intersect, yet the console logged the opposite result. Can anyone offer guidance on what might be going wrong here or suggest ways to debug this situation?
https://i.sstatic.net/W3mZ0.png
EDIT
Following a suggestion by Hectate, I added setFromObject() which resolved the initial problem. However, a new challenge emerged as the first box represents my camera. I aim to create a scenario where the camera, simulating a first-person view, collides with objects in the environment. To achieve this, I have hidden a square within an Object3D() to serve as a collision boundary.
Due to my translation of the player Object3D (for performance reasons), the original position remains unchanged, leading to either constant or absent intersection detection. Any thoughts on how to address this issue?
Here is the code snippet I use to control the player Object3D:
Keypress detection:
switch (e.key) {
case `z`:
moveForward = true;
break;
case `s`:
moveBackward = true;
break;
case `q`:
moveLeft = true;
break;
case `d`:
moveRight = true;
break;
}
In the animate function:
if (moveForward) player.translateZ(- .05);
if (moveBackward) player.translateZ(.05);
if (moveLeft) player.translateX(- .05);
if (moveRight) player.translateX(.05);
EDIT 2
Presented here is my full script.js:
import sets from './data/sets';
import ColladaLoader from 'three-collada-loader';
import BufferLoader from './modules/sound/BufferLoader';
import SpawnObject from './modules/render/SpawnObject';
import Controls from './modules/util/Controls';
import io from 'socket.io-client';
import {isEmpty} from 'lodash';
// Other imports...
// Main initialization function and event handlers...
animate();