Bounding box issue
Create a box around an object
HTML
<script src="https://unpkg.com/[email protected]/build/three.min.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/loaders/GLTFLoader.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/loaders/DRACOLoader.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/controls/OrbitControls.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/math/OBB.js"></script>
CSS
body {
background-color: #000;
margin: 0px;
overflow: hidden;
}
JavaScript
var mesh, renderer, scene, camera, controls, model, scale;
init();
animate();
function init() {
scale = 50;
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera( 20, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( scale, scale, 0 );
// controls
controls = new THREE.OrbitControls( camera, renderer.domElement );
// ambient
scene.add( new THREE.AmbientLight( 0xffffff ) );
// light
const directionalLight = new THREE.DirectionalLight(0xffffff, 10);
directionalLight.position.set(1, 2, 3);
scene.add(directionalLight)
// axes
scene.add( new THREE.AxesHelper( 100 ) );
const loader = new THREE.GLTFLoader();
loader.setCrossOrigin('anonymous');
const dracoLoader = new THREE.DRACOLoader().setDecoderPath('https://unpkg.com/[email protected]/examples/js/libs/draco/gltf/');
loader.setDRACOLoader(dracoLoader);
loader.load('https://rawcdn.githack.com/wetzzer/object/3f737e4ffd0379897776a9306391f389f5ceb82e/testA.glb', (gltf) => {
model = gltf.scene;
scene.add(model);
createBoundingBox(scene);
});
}
function createBoundingBox(scene) {
scene.traverse((child) => {
if (child instanceof THREE.Object3D && child.name.includes("Cube")) {
console.log("FOUND CUBE");
const aabb = new THREE.Box3().setFromObject(child);
const obb = new THREE.OBB().fromBox3(aabb);
// Visualize
const boxMaterial = new THREE.MeshBasicMaterial({ color: 0xFF0000, wireframe: true, depthTest: false });
const boxGeometry = new THREE.BoxGeometry(obb.halfSize.x * 2, obb.halfSize.y * 2, obb.halfSize.z * 2);
const box = new THREE.LineSegments(boxGeometry, boxMaterial);
child.userData.obb = obb;
...