Using Three.js, the loaded mesh's position displays variation compared to a basic geometry mesh

I've been attempting to position a mesh at a specific location, but I'm facing difficulties in achieving the exact placement I desire. While I can successfully position a simple sphere so that its left-most point aligns with the left border of my canvas, the same method doesn't seem to work for a more complex loaded mesh. I find this discrepancy puzzling.

To start off, I set up a basic scene:

// The bottom-left corner is considered as (0,0)
const camera = new THREE.OrthographicCamera(0, 1, 1, 0, 0, 3);
// Adding ambient light
const ambient = new THREE.AmbientLight(0x404040, 0.8); // Soft white light
scene.add(ambient);

camera.position.z = 1;
renderer.setSize(
    600, 600 // Ensuring a square canvas
);

Next, I load my mesh using objectLoader:

objectLoader.load(
    // Specifying resource URL as first parameter
    'some/url/to/my/object/',

    // Callback function upon successful loading
    function (object) {

        scene.add(object);

        object.scale.set(0.3, 0.3, 0.3) 
        object.position.set(0.5,0.5, 0) // Initial center position

        // Attempting to align the left-most point of the mesh with the canvas edge
        var box = new THREE.Box3().setFromObject(object);
        let width = box.max.x - box.min.x 
        object.position.x = width * 0.5; // Adjusting the position
        
        // For the right edge alignment
        const object2 = object.clone()
        scene.add(object2)
    
        object.position.x = 1 - (width * 0.5) // Adapting the position
    })

Despite these adjustments, there seems to be an offset affecting both objects equally. After careful observation, it appears that both objects are offset by roughly 0.035 units. I am determined to identify the source of this seemingly random offset.

In an effort to troubleshoot, I substituted the mesh with a simple sphere geometry. Surprisingly, the translation operation described earlier works flawlessly with the sphere:

const geometry = new THREE.SphereGeometry( 0.1, 32, 16 );
const material = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);

var sphereBox = new THREE.Box3().setFromObject(sphere);
let sphereBox_width = sphereBox.max.x - sphereBox.min.x
sphere.position.x = sphereBox_width * 0.5; // Position adjustment
sphere.position.y = 0.8; // Arbitrary placement

const sphere2 = sphere.clone()
scene.add(sphere2);
sphere2.position.x = 1 - (sphereBox_width * 0.5); // Same operation on other side

It's interesting to note that although the code implementation remains consistent, the positioning works seamlessly with spheres but not with human figure meshes. Any insights on how to accurately position object and object2 meshes at the borders, similar to what was achieved with the spherical objects? What could be causing the differing outcomes?

Answer №1

After spending a considerable amount of time, I finally managed to unravel the root cause of the issue.

My mistake was that I was adjusting the meshes based on the geometrical center of the mesh. It turns out that threejs actually defaults to using the volumetric center instead.

When dealing with symmetrical meshes, these two centers will be the same. However, for asymmetrical meshes, there can be significant differences. In my particular situation, the difference was quite subtle, which made it challenging to identify.

To set the center of a mesh to its geometric center (i.e., width * 0.5, height * 0.5) use the following code:

  mesh.geometry.center() # mesh refers to the mesh object

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

Transform a Mongoose object into a specific JSON schema

When retrieving data from MongoDB using mongoose as an ORM, I have a specific requirement. Instead of sending all the fetched information back to the client in the response, I need to convert the mongoose object into a JSON object that adheres to my cust ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

Explore the world of textures transferring from Maya to Three.js

I'm looking to convert a Maya model to JavaScript for a simple model with textures. The conversion works fine, but the textures are not showing up. Here is my code: var loader = new THREE.JSONLoader(); loader.load( "models/t2.js", function(geometry) ...

What could be causing the discrepancies in the sound of my JS audio-streaming code between x86 and x86_64 systems?

My application is designed to stream PCM binary data from the server directly to the Web Audio API. To achieve audio normalization, I utilize a DataView to convert the incoming data to Int16 format, where each sample is divided by 32768 before converting ...

Please execute the npm install command to install the readline-sync package in order to fix the error in node:internal/modules/c

Having trouble installing npm readline as it keeps showing errors, even after trying different solutions. https://i.sstatic.net/LoX6L.png https://i.sstatic.net/b8b7l.jpg Tried deleting folders and uninstalling nodejs but the issue persists. Need help fi ...

How can we prevent and remove extra whitespace characters such as new lines and line feeds in responseText?

I am troubleshooting an ajax script that is calling a php file. The php file is supposed to echo either "yes" or "no", which I intend to use for logical comparisons. However, when trying to compare the responseText in javascript to check if it matches "y ...

Initiate the IE driver in WebDriver NodeJS with the option to disregard protected mode settings and possibly introduce flakiness

I'm attempting to create a driver session using IE capabilities to bypass protected mode settings in Internet Explorer, but I'm unsure of the correct syntax. I've experimented with the following: var driver = new webdriver.Builder().wi ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

Unlocking Component Variables Beyond the Bounds - Vuejs

Suppose I have a compound called <myCompound>, how can I access the ref or variables from the outside? For example: myCompound.vue : <script setup> import { ref } from "vue"; const myString = ref("hi string"); </script&g ...

Is there a way to automatically execute this function when the React component is loaded, without the need for a button click?

After spending a few days trying to figure this out, I'm hitting a wall. This ReactJS project is new for me as I usually work with C#. The goal is to create a print label component that triggers the print dialog when a link in the menu is clicked. Cu ...

Tips for triggering the button command event using JavaScript

Is there a way to activate the button command event using JavaScript? I'm not referring to the BUTTON onclick event. ...

Difficulty in toggling on and off several form elements with JavaScript

Trying to control multiple form elements on an HTML page with JavaScript has presented a challenge for me. In my form, each row contains a checkbox that should enable/disable the elements on that row. The issue I'm facing is that only the first two f ...

Injector in Angular is a tool used for dependency injection

I have multiple components; I am using Injector in the constructor for encapsulation import { Component, Injector, OnInit } from '@angular/core'; @Component({ selector: 'app-base', templateUrl: './base.component.html', ...

Is there a way to successfully transfer both the event and props together?

For simplifying my code, I created a function that triggers another desired function when the Enter key is pressed. Here's an example of how it works: const handleKeyDown = (event) => { if (event.key === 'Enter') { event.preventDefa ...

Ways to manage a post request in Next.js

Attempting to establish a POST route within my api directory with next.js. After sending the data to the route, I am having difficulty parsing the data in order to properly store it in the database. What would be the most effective approach for managing ...

Having trouble displaying json data in an HTML file with d3.js

I am having trouble loading data from a json file into an HTML file and using D3 to visualize it. Even though the file loads correctly and is verified with a 200 status, the contents are interpreted as null. Below are the contents of the json file: [{"to ...

The process of transmitting messages back and forth between a popup script and a content script

I am in the process of developing a Chrome extension that involves sending data requests from a popup script to a content script (via a background script), analyzing the request on the content script, and then sending back a response (again through the bac ...

Sending arguments to Angular UI router template

My angular ui router is changing states/views as: $stateProvider .state({ name: 'home', url: '/', template: '<home-view></home-view>', }) Is it possible to ...

What is the best way to utilize mouseenter and mouseleave events concurrently?

I need some assistance with my website's star rating feature. When a user hovers over the stars, a popover should appear, and when they move their mouse away, the popover should disappear. Currently, I am using jQuery to achieve this functionality: $( ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...