I referenced an article on MDN for detecting collision between boxes and tested it out on this JSFiddle.
My goal is to move the red box and have the logs stop appearing once they are no longer colliding. However, I'm struggling with updating the Box3 (the bounding box of my box) to match the new position of the main box.
Currently, I am moving the box using keyboard keys like this:
checking if key is pressed
switch (e.key) {
case `z`:
moveForward = true;
break;
case `s`:
moveBackward = true;
break;
case `q`:
moveLeft = true;
break;
case `d`:
moveRight = true;
break;
}
in my animate function:
if (moveForward) redBox.position.z -= .05;
if (moveBackward) redBox.position.z += .05;
if (moveLeft) redBox.position.x -= .05;
if (moveRight) redBox.position.x += .05;
I thought updating the Box3 position would be a simple solution, but it seems adding the Box3 to my scene is restricted... So I'm unsure how to proceed with updating it.
var scene, renderer, camera;
var redBox, blueBox, redBbox, blueBbox;
var controls;
init();
animate();
function init()
{
renderer = new THREE.WebGLRenderer( {antialias:true} );
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize (width, height);
document.body.appendChild (renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
camera.position.y = 50;
camera.position.z = 50;
camera.position.x = 50;
camera.lookAt (new THREE.Vector3(0,0,0));
controls = new THREE.OrbitControls (camera, renderer.domElement);
redBox = new THREE.Mesh(
new THREE.BoxGeometry(3, 3, 3),
new THREE.MeshBasicMaterial({color: 0xff00000})//RED box
);
redBox.position.set(3, 3, 3);
redBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
redBbox.setFromObject(redBox);
const redBoxHelper = new THREE.BoxHelper(redBox, 0xFFFFFF);
scene.add(redBox, redBoxHelper);
blueBox = new THREE.Mesh(
new THREE.BoxGeometry(3, 2, 5),
new THREE.MeshBasicMaterial({color: 0x00000ff})//BLUE box
);
blueBox.position.set(3, 3, 3);
blueBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
blueBbox.setFromObject(blueBox);
const blueBoxHelper = new THREE.BoxHelper(blueBox, 0xFFFFFF);
scene.add(blueBox, blueBoxHelper);
window.addEventListener ('resize', onWindowResize, false);
}
function onWindowResize ()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize (window.innerWidth, window.innerHeight);
}
function animate()
{
//controls.update();
requestAnimationFrame ( animate );
if(redBbox.intersectsBox(blueBbox)){
console.log('intersection');
}
renderer.render (scene, camera);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/3587259/Code/Threejs/OrbitControls.js">
</script>