JSFiddle - React, Tailwind, and code Playground
by Cody Bennett
JavaScript
var camera, scene, renderer, geometry, material, mesh1, mesh2, objectBoundingBox1, objectBoundingBox2, count, outputLimit;
init();
animate();
function init() {
// Stops outputting to the console when this limit is reached so the console isn't spammed too much.
count = 0;
outputLimit = 10;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 500;
scene.add(camera);
// Mesh 1
geometry1 = new THREE.CubeGeometry(50, 50, 50);
material1 = new THREE.MeshNormalMaterial();
mesh1 = new THREE.Mesh(geometry1, material1);
mesh1.position.x = 0;
mesh1.position.y = 0;
mesh1.position.z = 0;
scene.add(mesh1);
// Mesh 2
geometry2 = new THREE.CubeGeometry(50, 50, 50);
material2 = new THREE.MeshNormalMaterial();
mesh2 = new THREE.Mesh(geometry2, material2);
mesh2.position.x = 0;
mesh2.position.y = 0;
mesh2.position.z = 0;
scene.add(mesh2);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
render();
// Bounding box 1
var objectBoundingBox1 = new THREE.Box3();
objectBoundingBox1.setFromObject( mesh1 );
// Bounding box 2
var objectBoundingBox2 = new THREE.Box3();
objectBoundingBox2.setFromObject( mesh2 );
// Check for collision
if (count < outputLimit) {
if (objectBoundingBox1.intersectsBox(objectBoundingBox2)) {
console.log('hit!');
} else {
console.log('no hit!');
}
count += 1;
}
}
function render() {
renderer.render(scene, camera);
}