Tips for aligning a mesh on the X and Y axes in three.js

Currently, I am aligning objects/models (mesh) in my scene by using the mesh.geometry.center() function.

This method helps position the object in the center based on its bounding box.

For static objects with a fixed size, like a cardboard box for example, this approach works perfectly without any issues.

However, when dealing with more intricate 3D models such as a bowling ball, jagged rocks, and the Eiffel Tower, the current method falls short. These detailed models end up being centered based on their overall shape which can lead to parts of the model protruding or floating awkwardly in space.

I am looking for a way to determine the center of each mesh only along the X and Y axes. This would allow me to place these complex models flat on an XY plane seamlessly without having to manually adjust the Z value. Is there a solution for this?

Answer №1

An effective method to achieve this for various objects or object hierarchies... First, determine the boundaries of the object by calculating its bounding box dimensions. Then, scale the object so that it fits within a range of 1 on the largest axis while maintaining centering on the x and z axes, with the y-axis serving as the reference point.

    var cent = new THREE.Vector3();
    var size = new THREE.Vector3();
    var bbox = new THREE.Box3().setFromObject(yourModel);
    bbox.getCenter(cent);
    bbox.getSize(size);

    //Normalize the object's scale
    var maxAxis = Math.max(size.x, size.y, size.z);
    yourModel.scale.multiplyScalar(1.0 / maxAxis);

    //Recalculate the updated/scaled bounding box
    bbox.setFromObject(yourModel);
    bbox.getCenter(cent);
    bbox.getSize(size);

    yourModel.position.x = -cent.x;
    yourModel.position.y = 0;
    yourModel.position.z = -cent.z;

Answer №2

BufferGeometry comes with a method called center, which centers the geometry based on the bounding box. However, it also unintentionally centers the object along the z-axis. To avoid this, here is a custom center method that focuses only on centering the object along the x and y axes.

// scale, adjust dimensions of yourMesh
// ..
const geometry = yourMesh.geometry;

geometry.computeBoundingBox();
const centerVector = new Vector3();
geometry.boundingBox.getCenter(centerVector).negate();
geometry.translate(centerVector.x, centerVector.y, 0);

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

Using a data loader with react-router

I am currently working on a react app where I have implemented routes using the new data loaders from react-router-dom import { RouterProvider, createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom'; import Home fr ...

There are three pop-up windows displayed on the screen. When each one is clicked, they open as intended, but the information inside does not

Every button triggers a unique modal window Encountering an unusual problem with Bootstrap 5 modal functionality. Within a webpage displaying a list of database entries (refer to the screenshot), each entry features three buttons to open corresponding mod ...

I am unable to retrieve values from the req.body object in Node.js

Can anyone assist with node.js? I am having trouble accessing the values in my req.body object. Here is how it is populated: { '{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670a060e0b270f0814130906 ...

What is the best way to ensure that my top menu remains fixed while scrolling?

Link to website: I am looking to have the top menu on my page remain fixed at the top of the screen as users scroll. Does anyone know if this is achievable, and if so, how can I implement it? ...

Tips for implementing an onclick jquery function within an input field

Just starting out with JavaScript and jQuery, I have a jQuery function that looks like this: $('.input-group .date').datepicker({ }); I want to apply it to the following HTML structure: <div class="input-group date" id="dp3"> <inp ...

The functionality of onClick and console.log seems to be malfunctioning on Nextjs

I'm currently learning NEXT but I've encountered some issues with certain functions "use client" import { useState } from 'react' export default function idk() { const [counter,setCounter]=useState(0) const add=()=> ...

Retrieve the API Url within an Angular application built with .Net Core

My current setup includes an API project and an Angular Project within the same .NetCore solution. The Angular Project makes API calls to the API project using a baseurl specified in the Environment.ts and Environment.prod.ts files. However, upon publish ...

Unable to locate request object during post request

I've created a pug form with the following structure: extends layout block content h1 David A Hines h2 #{posts[0].title} p #{posts[0].body} div form(action='/insert_post',method='post') div(id='title_div' ...

Configuring Azure Storage CORS settings for embedding video content

In my project, I am working on creating a panorama tour that includes additional content such as videos using three.js and React. The videos I am using are stored on a private Azure storage, where I generate SAS tokens for specific video files. When atte ...

Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM? In my specific case, I want my Vue instance to receive the action attribute of a form element. For example, this is how my HTML would look like (the ...

What is the best way to dynamically write a knockout data binding event using jQuery?

let $button = $('<input/>').attr({ type: 'button', value: data.styleData, id: buttonId, data - bind: event: { click: $parent.submitPopUp } }); An error is being displayed. ...

I am looking to utilize jQuery to dynamically update a selected checkbox through AJAX

I've been struggling to make my ajax json script update my HTML checked box with the value from the database, but so far I haven't had any luck. Any assistance would be greatly appreciated! Here's the JS code snippet: setInterval(functi ...

What is the reason behind having to refresh my ReactJS page despite it being built with ReactJS?

I have developed a task management application where users can input notes that should automatically update the list below. However, I am facing an issue where the main home page does not display the updated todos from the database unless I manually refres ...

"Navigate back with just a click - XSL button

My expertise in this area is limited. After some searching, I couldn't find exactly what I need. Hopefully, the solution is simple. I am currently developing a software control system with a built-in web server. Certain points during navigation requi ...

changing the action URL of a jQuery form dynamically upon submission

I am currently utilizing a jquery ajax form library and I would like to alter the action URL when submitting the form. Here is the HTML code: <div class="modal-body form"><?php echo form_open_multipart("#",array('id'=>'mng_form ...

How to handle uncaught errors in jQuery.ajax callback?

I am struggling with handling a callback throw in an Ajax callback. To illustrate this issue, I have created a minimal test case which can be found here (code provided below). Within the init() function, I instantiate a new object of the ResourceLoader cl ...

Experiencing difficulties when attempting to show or hide elements using jQuery

I spent several hours trying to figure this out and couldn't get it right. Is it feasible to create a jQuery script that will perform the following action when a <span> element is clicked: Check if any of the <p> elements are current ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

The Vue 2 watch feature may encounter difficulties with mixin data properties, however, it functions properly when the data property belongs to the

I recently attempted to refactor some code by moving certain functionalities to a vue mixin from the component itself, with the intention of reusing it in multiple components. The simplified version of the code looks like this: export default { data() { ...

conceal the bootstrap navigation bar while the page is being

Struggling to toggle a Bootstrap navbar on scroll? Need some guidance from the pros out there. I admit, my Bootstrap and jQuery skills are pretty basic. The browser console doesn't throw any errors, and I've experimented with fadeIn, fadeOut, add ...