Rotating a 3D object in Three.js around any axis using the Loop Rotation feature

I'm currently attempting to create a 3D object that rotates continuously on any axis, similar to a classic cube or sphere. However, I'm encountering an issue where the object is not moving at all and I'm unsure why. Here is the code I'm using:

var scene6, camera6, renderer6, light, shipMtl, shipObj;

function init() {
    scene6 = new THREE.Scene();
    camera6 = new THREE.PerspectiveCamera(35, 1, 1, 1000);
    camera6.position.z = 400;

    //LIGHTS
    light = new THREE.PointLight(0xffffff, 2, 0);
    light.position.set(200, 100, 300);
    scene6.add(light);


    //3D MODEL
    shipMtl = new THREE.MTLLoader();
    shipMtl.load('../models/spaceCraft1.mtl', function(materials) {
        materials.preload();
        shipObj = new THREE.OBJLoader();
        shipObj.setMaterials(materials);
        shipObj.load('../models/spaceCraft1.obj', function(object) {
            object.scale.set(10, 10, 10);
            object.rotation.x += .01;
            scene6.add(object);
        });
    });

    renderer6 = new THREE.WebGLRenderer({ canvas: document.getElementById('model'), antialias: true });
    renderer6.setClearColor(0x000000);
    renderer6.setPixelRatio(window.devicePixelRatio);

    animate6();
}

function animate6() {

    requestAnimationFrame(animate6);
    renderer6.render(scene6, camera6);

}

window.onload = init;

Any assistance you can provide would be greatly appreciated.

Answer №1

The object's rotation will only be altered once - during the loading of the model.

If you wish for the object to rotate continuously, you must update its rotation every frame. To achieve this, you should move the object.rotation.x += 0.01 line inside the animate() function.

var scene6, camera6, renderer6, light, shipMtl, shipObj;
var obj; // reference to the loaded model

function init() {
    scene6 = new THREE.Scene();
    camera6 = new THREE.PerspectiveCamera(35, 1, 1, 1000);
    camera6.position.z = 400;

    //LIGHTS
    light = new THREE.PointLight(0xffffff, 2, 0);
    light.position.set(200, 100, 300);
    scene6.add(light);

    //3D MODEL
    shipMtl = new THREE.MTLLoader();
    shipMtl.load('../models/spaceCraft1.mtl', function(materials) {
        materials.preload();
        shipObj = new THREE.OBJLoader();
        shipObj.setMaterials(materials);
        shipObj.load('../models/spaceCraft1.obj', function(object) {
            object.scale.set(10, 10, 10);
            // rotation adjustment should be done in the animate function
            obj = object; // save object as global reference
            scene6.add(object);
        });
    });

    renderer6 = new THREE.WebGLRenderer({ canvas: document.getElementById('model'), antialias: true });
    renderer6.setClearColor(0x000000);
    renderer6.setDevicePixelRatio(window.devicePixelRatio);

    animate6();
}

function animate6() {
    requestAnimationFrame(animate6);

    obj.rotation.x += 0.01;

    renderer6.render(scene6, camera6);
}

window.onload = init;

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

Reload the page when the value reaches 1

Hello, I am currently working on creating a system where my index page refreshes when a value in my database is set to 1. However, I am having trouble with the code as only my index.php is not refreshing. index.php <script> interval_timer = setInt ...

Error encountered: Firebase cloud function in Node.js V10 has experienced a parsing issue due to an unexpected token 'select

Each time I try to deploy my cloud function, I encounter a Parsing error: Unexpected token selectWinner. I attempted to resolve this by updating the parser options in .eslintrc.json to utilize ecmaVersion 2017, but unfortunately, that did not solve the is ...

Guide to creating a transition effect for opacity in React Fiber and Drei by utilizing the <Text> component

I am looking to create an animation that transitions opacity from 0 to 1 using the react-fiber/drei component. My attempt with react-spring/three didn't yield the desired results: `import { useEffect, useRef, useState} from "react"; import ...

Limit the use of map() to only the immediate children of the parent element

Currently, I am utilizing the map() function to target the child elements within my dropzone: $('#DropZone div').map(function(i, item){ }) The structure of the dropzone is as follows: <div id="DropZone"> <div id="firstImage"> ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

The db.all method does not provide an array as its return variable

Seeking to extract an array from the db.all function to incorporate it into a custom JSON object for a response. Various attempts have been made including using Object.values(members), members.fulfillmentValue, and some PROMISE methods discovered on Stack ...

``motioning a component beneath another component that may be in a state

Having an issue with my CSS. I have some elements generated by JavaScript and when hovering over them, another element is displayed below the others for some reason. Here's the CSS related to this problem: .hiddenTextjob { display:none; ...

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

Unable to load the requested resource: net::ERR_FAILED

I am facing an issue while trying to write React code. When using Chrome, I encountered the following warning: Access to XMLHttpRequest at 'file:///D:/programe/code/Vscode/ReactDemo/HelloWorld/test.js' from origin 'null' has been block ...

Converting MSK time to SST time using JavaScript: A Handy Guide

My API returns time in the format: 07:00 PM This timestamp is based on MSK (Moscow Standard Time) and I need it converted to SST (Singapore Standard Time) using either JavaScript or an npm package. ...

Retrieve the original jqXHR object from the success callback of the $.ajax function

My original task is as follows: Execute a jQuery.ajax() request. Upon success, perform additional checks on the data received from the server. If these checks fail, reject the promise for further handling. After researching extensively online, I came up ...

What is the best way to create a line break within a loop in React?

I have a react component that I need to format into multiple lines, specifically having 2 boxes on top and 3 below in a looped return. The desired layout is to stack the boxes in 2x2 or 2x3 depending on the total number of boxes generated by the loop. So, ...

Using the integrated pipeline mode in IIS is necessary for this operation to be

My aspx page has an ajax call which looks like this: $.ajax({ url: "/SiteAdmin3/UpsIntegration.aspx/addUpdatePackageData", data: JSON.stringify({ '_OrderNumber': $("#txtOrderNumber ...

"Could you please help me understand the process of receiving a JSON in an Express

When working with React, I encountered an issue where the JSON data sent to me from the front-end is in a strange format (an object with the data as a string). I am unsure how to convert it back into the object type. This is what I send: const data = { ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Shifting the MUI DataGrid Pagination table to the left with CustomPagination: A step-by-step guide

Hey everyone, I am currently diving into the MUI data grid to gain a better understanding. In order to meet my design requirements for a table view, I have incorporated the DataGrid component from MUI. For pagination, I am utilizing their custom implementa ...

What is the best way to incorporate AngularJS data into JavaScript for use in Google Chart?

How can I leverage my AngularJS scope data in a Google Chart or JavaScript? Below is my AngularJS file: angular.module('reports').controller('ReportInfoCtrl', ['$scope', 'reports', '$rootScope','$loca ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

Use $.ajax to display the menu by capturing an array of elements {0}

Whenever I click on one of the DIV elements, a menu pops out on the side displaying more information about the clicked element. I can determine which element I'm clicking on, but I'm struggling to pass that information from jQuery to the PHP pag ...

Experiment with jQuery and JavaScript compatibility specifically on Internet Explorer 6

Seeking advice on the most effective method to test my web app using IE6. I currently have IE8 installed on my computer, and am considering utilizing a Virtual Machine. Are there any other alternatives worth exploring? It is imperative that my jQuery and ...