Rotating an object around another object in a 3D matrix axis using Three.js

I currently have the ability to rotate one axis.

Here is the code that's working now: 
https://codepen.io/itzkinnu/full/erwKzY

Is there a way to rotate an object on a random axis instead of just one fixed axis?

Maybe something similar to this example: https://i.sstatic.net/PH6aj.jpg

Answer №1

If you desire an object to be positioned relative to another object, then the object must be included as a child of the reference object.

Utilize the Object3D.add method to add a child to an object.

Check out the following example:

(function onLoad() {
  var container, loader, camera, scene, renderer, controls, mesh, child;
  
  init();
  animate();

  function init() {
    container = document.getElementById('container');
    
    renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 100);
    camera.position.set(0, -4, -1.5);

    loader = new THREE.TextureLoader();
    loader.setCrossOrigin("");

    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xffffff);
    scene.add(camera);
    window.onresize = resize;
    
    var ambientLight = new THREE.AmbientLight(0x404040);
    scene.add(ambientLight);

    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    directionalLight.position.x = -0.75;
    directionalLight.position.y = -0.5;
    directionalLight.position.z = -1;
    scene.add( directionalLight );

    controls = new THREE.OrbitControls(camera, renderer.domElement);
    
    var axis = new THREE.AxesHelper(2);
    scene.add(axis);
    
    var material = new THREE.MeshPhongMaterial({color:'#f08080'});
    var geometry = new THREE.BoxGeometry( 1, 1, 1 );
    mesh = new THREE.Mesh(geometry, material);

    var material2 = new THREE.MeshPhongMaterial({color:'#8080f0'});
    var geometry2 = new THREE.BoxGeometry( 1, 1, 1 );
    child = new THREE.Mesh(geometry2, material2);
    child.position.x = 1.5;

    mesh.add(child);
    scene.add(mesh);
  }

  function resize() {
    var aspect = window.innerWidth / window.innerHeight;
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = aspect;
    camera.updateProjectionMatrix();
  }

  function animate() {
  
    child.position.set(0, 0, 0);
    child.rotateY(0.02)
    child.translateX(1.5);

    mesh.position.set(0, 0, 0);
    mesh.rotateZ(0.01);
    mesh.translateX(1.0);
    
    requestAnimationFrame(animate);
    render();
  }

  function render() {
    renderer.render(scene, camera);
  }
})();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div id="container"></div>

Answer №2

Thank you Rabbid76 for the quick response. It actually helped.

I have added

child.rotateY(0.02);

to the above code in animate function to rotate in a random axis.

May I know how to make the child box self-rotate?

(function onLoading() {
  var container, loader, camera, scene, renderer, controls, mesh, child;
  
  initialize();
  startAnimating();

  function initialize() {
    container = document.getElementById('container');
    
    renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 100);
    camera.position.set(0, -4, -1.5);

    loader = new THREE.TextureLoader();
    loader.setCrossOrigin("");

    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xffffff);
    scene.add(camera);
    window.onresize = resizeHandler;
    
    var ambientLight = new THREE.AmbientLight(0x404040);
    scene.add(ambientLight);

    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    directionalLight.position.x = -0.75;
    directionalLight.position.y = -0.5;
    directionalLight.position.z = -1;
    scene.add( directionalLight );

    controls = new THREE.OrbitControls(camera, renderer.domElement);
    
    var axis = new THREE.AxesHelper(2);
    scene.add(axis);
    
    var material = new THREE.MeshPhongMaterial({color:'#f08080'});
    var geometry = new THREE.BoxGeometry( 1, 1, 1 );
    mesh = new THREE.Mesh(geometry, material);

    var material2 = new THREE.MeshPhongMaterial({color:'#8080f0'});
    var geometry2 = new THREE.BoxGeometry( 1, 1, 1 );
    child = new THREE.Mesh(geometry2, material2);
    child.position.x = 1.5;

    mesh.add(child);
    scene.add(mesh);
  }

  function resizeHandler() {
    var aspect = window.innerWidth / window.innerHeight;
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = aspect;
    camera.updateProjectionMatrix();
  }

  function startAnimating() {
  
    child.position.set(0, 0, 0);
    child.rotateY(0.02)
    child.translateX(1.5);

    mesh.position.set(0, 0, 0);
    mesh.rotateZ(0.01);
    mesh.translateX(1.0);
    
    requestAnimationFrame(startAnimating);
    renderScene();
  }

  function renderScene() {
    renderer.render(scene, camera);
  }
})();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div id="container"></div>

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

Accessing Struts2 tag attributes with JavaScript

Currently, I am using struts2 with jsp. Within the JSP file, there is a table with several rows of data. To display the row data in the table, iterators are being used. Each row includes a button that allows the user to update the row's data, such as ...

What is the best method for retrieving the selected itemsPerPage in Vuetify's data-table in version 2.0

Recently, I've been struggling to retrieve the selected items-per-page on a Vuetify data-table due to some recent changes. I came across this helpful example: How to set initial 'rows per page' value in Vuetify DataTable component? Here is th ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...

Encountering ERR_EMPTY_RESPONSE when using the $.POST method

I have been struggling with a issue on my social networking site that includes chat functionality. I have utilized the $.post method extensively across multiple pages, and it generally functions well except for a specific page called message.php where user ...

What is the best way to reach nested iframes?

I am looking for a solution to send post messages (window.postmessage) to iframes. Currently, it is functioning properly with a single iframe inside the parent page. However, I want it to also work for nested iframes. Here are the criteria: I should on ...

Using a Promise to signal the completion of certain tasks

In our application, we have multiple controllers assigned to different tabs/pages. I am looking for a way to signal the completion of a task in one controller so that it can be used in another controller. I believe Promises are the solution for this, and I ...

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

Error occurred: Unable to access 'client' property as it is undefined. Process will continue running

Hi there! I'm currently working on building a key bot for my website, but I keep encountering this error UNCAUGHT EXCEPTION - keeping process alive: TypeError: Cannot read properties of undefined (reading 'client') along with another one rel ...

The Material-UI selector isn't functioning properly for me

I recently tried to incorporate a material-ui selector example into my project by referring to the code fragment obtained from an example on Github. import React from "react"; import {withStyles} from "material-ui/styles"; import Select from "material-ui/ ...

Polygon Shapes in Motion

Rotating Asteroids with Mathematical Precision In my quest to create aesthetically pleasing rotating asteroids (polygons), I have delved into the realm of mathematical equations. It all begins with assigning a rotation velocity to each individual asteroid ...

Issue: The hydration process has failed due to a discrepancy between the initial UI and the server-rendered content when utilizing the Link element

Exploring Next.js, I stumbled upon the <Link/> component for page navigation. However, as I utilize the react-bootstrap library for my navbar, it offers a similar functionality with Nav.Link. Should I stick to using just Link or switch to Nav.Link? ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

Node.js throws an error with the message "Unexpected token *" while utilizing the robe

Currently, I'm working on a Node.js application where I'm attempting to utilize the node module named robe. Unfortunately, I encountered an error message when trying to launch the app: function* promiseToGenerator(promise) { ^ Error l ...

Determining the nearest upcoming date from a JSON dataset

Looking to find the nearest date to today from the array "dates". For example, if today is 2011-09-10 -> the next closest date from the JSON file is "2012-12-20" -> $('div').append('date1: ' + dates.date1); For example 2, if tod ...

JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it. Below is the code I currently have: <!DOCTYPE html> <html x ...

jquery-validation error in gulp automations

I've encountered a sudden error in my gulp build related to jQuery validation. There haven't been any recent changes that would trigger this issue. Interestingly, one of my colleagues is experiencing the same problem, while another one is not. We ...

Encountered a CastError in Mongoose when trying to cast the value "Object" to a string

I am struggling with a Mongoose CastError issue within my Node.js API. The problem arises at a specific route where data is being returned appended with some additional information. Despite finding various solutions for similar problems, my scenario seems ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...

Merging two individual JavaScript scripts to ensure seamless functionality for both

I am facing a challenge with utilizing two scripts simultaneously: Script 1: $(document).ready(function () { $(".tabContent").not(":first").hide(); $("ul.tabs li:first").addClass("active").show(); $("ul.tabs li").click(function () { $ ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...