Loading a three.js model with OBJMTLLoader and spinning it around

After successfully using the OBJMTLLoader class for one obj file and achieving proper rotation around a fixed point on the object with object.rotation.y -= 0.5, I encountered an unexpected issue when trying to replicate the same code with a different .obj file. Instead of maintaining a fixed rotation point, the rotation now seems to be revolving in a circular motion, almost around the camera itself. Any insights into why this change occurred despite using the same code?

Thank you!

EDIT:

var OBJLoaded;    

function init()
{
    container = document.getElementById('player');
    camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1,  2000);
    camera.position.x = 110;
    camera.position.z = -160;
    camera.position.y = 15;

    // camera.position.z = 40;
    // camera.position.y = 2;

    //scene
    scene = new THREE.Scene();

    var ambient = new THREE.AmbientLight( 0x444444 );
    scene.add( ambient );

    var directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.set( 100, 90, 200 );
    scene.add( directionalLight );

    //model
    var loader = new THREE.OBJMTLLoader();
    //loader.load('./assets/Stereo_LowPoly.obj', './assets/Stereo_LowPoly.mtl',    function(object)
    loader.load('./assets/studio_beats.obj', './assets/studio_beats.mtl', function(object)
    { 
        OBJLoaded = object;
        console.log(object);
        scene.add( object );
    });

    renderer = new THREE.WebGLRenderer({alpha: true});
    renderer.setClearColor(0x000000, 0);
    renderer.setSize($('#player').width(), $('#player').height());
    container.appendChild(renderer.domElement);

    scene.add(camera);
}

function animateBoombox()
{
    requestAnimationFrame(animateBoombox);
    render();
}   

function render()
{
    var rotSpeed = 0.004;
    if (OBJLoaded) 
    { 
        OBJLoaded.rotation.y -= rotSpeed;
    }
    renderer.render(scene, camera);
}

The sections that are commented out (camera and object load) pertain to the previous object that was loaded and worked correctly. However, after uncommenting them for the new object, the functionality is not consistent.

Answer №1

The item you've imported contains a pivot point from the software used to create the model... You must adjust the object's pivot point before loading it with three.js.

If you're unsure how to do this, follow my example in the loader callback:

            var importer = new THREE.OBJMTLLoader();
            importer.load('your_model.obj', 'your_model.mtl', function (item) {
                item.traverse(function (element) {
                    element.centerpoint = new THREE.Vector3();
                    for (var index = 0; index < element.geometry.vertices.length; index++) {
                        element.centerpoint.add(element.geometry.vertices[index].clone());
                    }
                    element.centerpoint.divideScalar(element.geometry.vertices.length);
                    var shift = element.centerpoint.clone();
                    element.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-shift.x, -shift.y, -shift.z));
                    element.position.copy(element.centerpoint);
                    element.geometry.computeBoundingBox();
                });
            });

Next, proceed to rotate your 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

Make sure that the equal sign is never utilized at the beginning of a form input field

Seeking a method to prevent the use of the "=" character in any input field within a form. <form> <input name="email" type="email" placeholder="Email" required=""> <input name="last name" type="text" placeholder="Last Name"> ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...

jQuery disregards the HTTP request method and adds unusual query parameters to the URL

My current project involves utilizing a web service that requires POST requests containing a JSON string in the body. I've encountered some challenges while attempting to interact with this web service using jQuery: 1) jQuery appears to default to th ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...

What is the most effective approach to combining two arrays of objects in JavaScript by identifying commonalities?

Looking to merge two arrays of objects: var arr1 = [{id:1, name:John },{id:2, name:Adam }] var arr2 = [{id:1, address:NY, number: 200}, {id:2, address:LA, number: 300}] with the desired output being: var newArr = [{id:1, name:John, address:NY, number: 20 ...

Vuejs may encounter challenges with v-model when numerous items are present on the page

My simple page consists of a form at the top for submitting data and a list below that, as shown in the image: https://i.sstatic.net/3WjY2.png The list is populated with data from an api, each object having only 4 properties. Currently, there are a total ...

Tips for locating a specific value within an array using ReactJS

I have a set of dates provided by the back-end that I need to work with in order to perform a specific check. If the list contains dates from the month of March, I should display the events for March, and the same for April, and so on. My task involves se ...

Ways to update the entire MobX observable array with new values

When working with MobX, is there a way to update the values of an observable array without re-setting every value? At first glance, one might think the solution is: let arr = observable([]); autorun(() => { console.log('my array changed!') ...

Chart.js encounters difficulties displaying the chart due to the data in reactjs

My goal is to utilize chartjs-2 to showcase a bar graph with data. Below is the code I've implemented: import React from "react"; import { Bar, Line, Pie } from "react-chartjs-2"; export default class App extends React.Component { constructor(pro ...

The functionality of the Bootstrap 4 Carousel featuring multiple items is experiencing malfunctions

I'm encountering an issue with my Bootstrap 4 card carousel. When the next or prev buttons are clicked, there is a strange transition effect. Additionally, in the mobile version, the buttons do not work properly. It seems that when the card slides to ...

Send a JavaScript variable to Twig

I am trying to pass a JavaScript variable to a twig path but the current method I am using is not working as expected. <p id="result"></p> <script> var text = ""; var i; for (varJS = 0; varJS < 5; varJS++) { text += "<a href= ...

jQuery swap- enhancing the appearance of numerical values

I am looking to customize specific characters within my <code> tag. While searching online, I came across the .replace() function but encountered issues when trying to style numbers. My goal is to change their appearance without altering the text its ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

issue with logging in, token verification failed

My current project involves creating a login system with authorization, but for some reason the token is not being transferred properly. const path = require('path'); const express = require('express'); const bodyParser = require(' ...

Reversing the order of input-group-addon and input in bootstrap on mobile devices

I attempted to adjust the layout of a bootstrap input-group-addon on mobile devices by using two input elements and manipulating their display and visibility properties. From a design standpoint, I achieved the desired result as the input is now positione ...

Disabling vertical scrollbar in textarea within Bootstrap modal using CSS, jQuery, and C# in .NET MVC framework

I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...

What's the issue with my ExpressJS req.query not functioning as expected?

My NodeJS repl setup includes an input, button, and h1 element. The goal is to update the HTML inside the h1 element with the value of the input upon button click. Here's a glimpse of my code: index.js: const Database = require("@replit/database ...

Is there a way to implement a confirmation form within the properties_list view to ensure the user intends to delete the property

Is there a way to modify the code below so that instead of directly deleting the property, a confirmation form (such as a modal) is displayed for the user to decide whether to proceed with the deletion or not? views.py def property_list(request): proper ...

Can halting an ajax function mid-process prevent it from finishing?

My objective is to convert a video using ffmpeg, which tends to take a considerable amount of time to complete. I'm considering sending an ajax request to the server for this task, but I don't want the user to have to wait until the video convers ...

Are strings in an array being truncated by Firebug console log?

I have a unique function for logging messages to the firebug console that I'd like to share: // Just having fun with names here function ninjaConsoleLog() { var slicer = Array.prototype.slice; var args = slicer.call(arguments); console.lo ...