Forming a BoxBufferGeometry using the dimensions from Box3

I'm looking to generate a box mesh within a three.js scene, with the points of the box mesh matching the bounding box of an existing object in the scene.

I attempted to create the box mesh from box3 using the method outlined below, but I'm not achieving the correct outcome:

let threeObject = the existing object in the scene;
let boundingBox = new THREE.Box3();
boundingBox.setFromObject(threeObject);

let geometry = new THREE.BufferGeometry();
let vertices = new Float32Array( [
boundingBox.min.x, boundingBox.min.y, boundingBox.min.z,  
boundingBox.min.x, boundingBox.max.y, boundingBox.min.z, 
boundingBox.min.x, boundingBox.min.y, boundingBox.max.z, 
boundingBox.min.x, boundingBox.max.y, boundingBox.max.z, 
boundingBox.max.x, boundingBox.min.y, boundingBox.min.z,  
boundingBox.max.x, boundingBox.max.y, boundingBox.min.z, 
boundingBox.max.x, boundingBox.min.y, boundingBox.max.z, 
boundingBox.max.x, boundingBox.max.y, boundingBox.max.z,
] );
geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
let material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
let mesh = new THREE.Mesh( geometry, material );
viewer.scene.add(mesh);

Any advice on how to properly create a mesh box from box3? Your assistance is greatly appreciated!

Answer №1

Converting Box3 to BoxBufferGeometry in Three.js may not have an automatic method, but here's a workaround that worked for me.

const threeObject = existing object in the scene;
const box3 = new THREE.Box3();

// Set Box3 to fit the object size as a bounding box
box3.setFromObject(threeObject);

// Create a BoxGeometry with the same dimensions as Box3
const dimensions = new THREE.Vector3().subVectors(box3.max, box3.min);
const boxGeo = new THREE.BoxGeometry(dimensions.x, dimensions.y, dimensions.z);

// Adjust the position of the new mesh to align with the original object
const matrix = new THREE.Matrix4().setPosition(dimensions.addVectors(box3.min, box3.max).multiplyScalar(0.5));
boxGeo.applyMatrix4(matrix);

// Create a mesh
const mesh = new THREE.Mesh(boxGeo, new THREE.MeshBasicMaterial( { color: 0xffcc55 } ));

Answer №2

Your code contains an array called vertices which is meant to hold vertex data but is actually representing face/triangle definitions. Consequently, when rendering this geometry data, you end up with random triangles instead of visualizing a box.

To address this issue, consider adding an index to your geometry that accurately represents the face definitions based on your vertices. Understanding the distinction between indexed and non-indexed geometries is crucial in this context. I recommend delving into the official documentation page of THREE.BufferGeometry to gain insights. You will find official code examples for both types of geometries.

Version: three.js R107

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I determine if a specific button has been clicked in a child window from a different domain?

Is there a method to detect when a specific button is clicked in a cross-domain child window that cannot be modified? Or determine if a POST request is sent to a particular URL from the child window? Below is an example of the HTML code for the button tha ...

Leveraging Swift's self within Javascript for interacting with Swift class properties and methods

In a project I am working on, I use a JS method called function jsMethod(selfRef) from a Swift class. Let's say we have a class A where this method is invoked. The selfRef parameter holds a reference to the instance of class A. How can I utilize this ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...

How to choose between GET/POST and USE in ExpressJS for URL filtering

router.get('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) VS router.use('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) Could someon ...

Display successive slidedown notifications consecutively

I want to implement a feature that shows slide down alerts using angularjs. Here is the code I have written: function LoginController($scope, $timeout) { $scope.alerts = [{ name: "Alert 01 something something" }, { name: &qu ...

Getting console data in AngularJS can be achieved by using the console.log()

This log in the console is functioning correctly. Is there a way to retrieve this information for the HTML? ProductController.js $scope.selectedProduct = function(product) { console.log(product.post_title); console.log(product.ID); console.l ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Surprising outcomes when using MongooseJS's findOne() method

Currently utilizing Mongoose as the Object Document Mapper (ODM) alongside NodeJS, but struggling with comprehending how error handling functions. It seems to be working, however the implementation appears incorrect and does not align with the documentatio ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Responsive Grey Tiles for Google Maps v3

I've successfully implemented Google Maps V3 in my project, but I'm encountering an issue with grey tiles appearing on the map. I attempted to fix this problem by triggering a resize event using the following code snippet: google.maps.event.trig ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

What could be causing my randomly generated value to be overwritten so quickly?

I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall(), getRandomIntX(), and getRandomIntY(). However, the random value seems to be constantly overwritten. How can I resolve this problem? ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

What triggers the onmouseout event to occur?

Is the event triggered continuously whenever the mouse is not hovering over the element? Or is it a one-time action when the mouse exits the element? This distinction is crucial for me to determine when the mouse pointer leaves the element, while only wa ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Using React components to create an anchor element for a popover display

Hey, I'm just starting out with React and trying to wrap my head around Hooks like useState. It's a bit challenging for me, and I want to keep things simple without making them too complex. I've encountered an issue when transitioning a Rea ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

Issues arise with the Node EJS module due to the malfunction of the include

Struggling with incorporating HTML snippets into my index.html, even after reviewing the EJS documentation. Directory Structure: project -public --assets ---css ---images ---js --Index ---index.html + index.css and index.js --someOtherPageFolder -views - ...