Unable to establish the local origin for the OBJMTLLoader element within the scene

I am currently working on a project using Three.js to create a dynamic scene where objects can be manipulated. I have successfully loaded objects using the OBJMTLLoader, but I am facing an issue with their origins. The objects still retain their original origin positions, causing them to snap back when moved. Despite researching solutions involving centroids and bounding boxes, I keep encountering undefined errors. Any assistance on this matter would be greatly appreciated!

loader.load('example.obj', 'example.mtl', function (object) {
            object.position.y = -50; // Setting new origin
            object.scale.set(scale, scale, scale);
        });

Below is the code snippet for moving the objects:

function onDocumentMouseMove(event) {
    event.preventDefault();
    mouse.x = ( (event.clientX - container.offsetLeft) / container.clientWidth ) * 2 - 1;
    mouse.y = -( (event.clientY - container.offsetTop ) / container.clientHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    if (SELECTED) {
        var intersects = raycaster.intersectObject(plane);
        SELECTED.position.copy(intersects[0].point.sub(offset));
        return;
    }

    var intersects = raycaster.intersectObjects(objects);
    if (intersects.length > 0) {
        if (INTERSECTED != intersects[0].object) {
            INTERSECTED = intersects[0].object;
            plane.position.copy(INTERSECTED.position);
            plane.lookAt(camera.position);
            updateLightPosition();
        }
        container.style.cursor = 'pointer';
    } else {
        INTERSECTED = null;
        container.style.cursor = 'auto';
    }
}

// More functions...

Answer №1

One issue arises due to the fact that the object's position depends on the plane and how objects are grouped together. The root of the problem can be found in the section where the INTERSECTED block from the onDocumentMouseMove() event is located.

This particular block fails to activate because the raycaster does not recursively scan through the objects array. To resolve this, a simple adjustment needs to be made by adding a second parameter of true to the intersectObjects() function.

var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
    if (INTERSECTED != intersects[0].object) {
        INTERSECTED = intersects[0].object;
        plane.position.copy(INTERSECTED.position);
        plane.lookAt(camera.position);
        updateLightPosition();
    }
    container.style.cursor = 'pointer';
} else {
    INTERSECTED = null;
    container.style.cursor = 'auto';
}

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

What is the best way to store checkbox statuses in local storage and display them again in a JavaScript to-do list?

I'm currently working on a to-do list application using basic JavaScript. One issue I'm facing is saving the checked status of the checkbox input element and displaying it again after the page is refreshed. Since I'm still learning JavaScrip ...

The content is not displayed in the d3 visualization

While examining the code of this visualization found at http://bl.ocks.org/mbostock/4062045, I noticed that the name from the JSON file is not displaying alongside the nodes. Even though the code includes: node.append("title").text(function(d) { return ...

Refresh database records

I am currently using grails and I am exploring ways to update my database table utility by selecting values from two drop down menus. These drop down menus are populated with values from the database based on user selections from another drop down menu. My ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...

Issue with isNan() and typeof in React framework

I'm attempting to create a field in the react-bootstrap component that only accepts numeric input. I know there is a type="number" attribute that can be used, but it's currently set to password to mask the input. Initially, I tried this approach ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

Creating a clickable div using JavaScript: A step-by-step guide

paramToExternalFile = 'all'; var div = document.createElement('div'); div.style.background = '#D8D8D8'; div.innerHTML = '<a href=' + xml_list_externalFile_SNS1 + paramToExternalFile + '/' + letters + &a ...

How can you use jQuery to display an image when hovering over text?

Looking for a tutorial or script that displays an image when hovering over HTML text with the mouse? ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

Utilize an array with dynamic referencing

I am attempting to reference a single index out of 30 different indices based on the user's actions, and then utilize ng-repeat to iterate through each item in the index. Controller: $scope.meals = [ { title: 'Abs', url:"#/app/mworkout ...

Error encountered while using VueJS: The Register component was not recognized as a

Encountering issues with the registration component in VueJS. I acquired the component from https://github.com/wanxe/vue-button-spinner via npm install. Subsequently, I integrated the code into my Laravel 5.5 app.js file. The contents of my app.js: requi ...

Record the cumulative amount computed using an asynchronous callback

If I use code similar to the one below, I am able to obtain the total byte size value every time a file is added. How can I log out only the total files size after it has been calculated in the fs.stat callback? var fs = require('fs'); var to ...

Develop an asynchronous function that can fetch a result at a later time within an Express route

I need to retrieve an Excel file from Box.com using their API and then convert the Excel data into JSON format. Afterwards, I plan to display this JSON data using Express and Handlebars. Below is the function I've created for fetching the Excel file ...

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

Activate AngularJS autocomplete when populating the input field using JavaScript

I'm currently facing an issue with updating the value of an input field on a website using JavaScript. Although I can successfully update the input field's value, I find that I am unable to trigger the autocomplete feature. Interestingly, when ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

Operating a slider on a web page built with HTML

I am currently working on developing a loan calculator that involves two range sliders interacting with each other to display monthly payments in a label. Here are the specific requirements: Display only 5 values on the "Month" range slider: 12,18,24,30,3 ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

Tips for rearranging array position retrieved from API in Vue.js

props: { groups: Array, }, computed: { groups: function(arr) { alert('hi') } }, <div v-for="(item, index) in groups" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSele ...

When working in three.js, it's important to remember that geometry.faceVertexUvs[0][0][index] does not equate to geometry.vertices

From what I gather, the uv coords ("texels") of each vertex in a mesh can be accessed using: geometry.faceVertexUvs[ materialIndex ][ faceIndex ][ vertexIndex ] The issue I'm facing is that the vertexIndex seems to have a different mapping order com ...