Orbiting ThreeJS object positioned at the coordinates (0,0,0)

I have set up a ThreeJS Scene similar to the image provided. The issue I'm facing is when trying to rotate Obj2 vertically around Obj1, it ends up rotating around the Z axis instead of the center point (0,0,0). My goal is for Obj2 to orbit exclusively around Obj1 (positioned at (0,0,0)) without rotating around any other axis.

function configureObj2PositionHorizontally(angleInDegree) {
  radianAngle = angleInDegree * oneDegreeInRadians;

  obj2Mesh.position.x = distance * Math.cos(radianAngle);
  obj2Mesh.position.z = distance * Math.sin(radianAngle);

  console.log(radianAngle, distance);
}

function configureObj2PositionVertically(angleInDegree) {
  radianAngle = angleInDegree * oneDegreeInRadians;

  obj2Mesh.position.y = distance * Math.sin(radianAngle);
  obj2Mesh.position.z = distance * Math.cos(radianAngle);

  console.log(radianAngle, distance);
}

To address this behavior, how can I ensure that Obj2 orbits only around Obj1? Any suggestions or solutions would be greatly appreciated!

You can view the JSFiddle sample code here: https://jsfiddle.net/janithsg/y8upn26v/25/

Answer №1

To achieve the desired effect, consider creating a group aligned with Obj1's position, then adding Obj2 to this group and rotating it around its Y and X axes (if Obj2 is initially displaced along the Z axis).

This snippet of code accomplishes the task:

const obj1Mesh = new THREE.Mesh(
  new THREE.SphereGeometry(0.5), 
  new THREE.MeshBasicMaterial({ color: 0xffff00 })
)
scene.add(obj1Mesh)

const obj2Mesh = new THREE.Mesh(
  new THREE.SphereGeometry(0.2), 
  new THREE.MeshBasicMaterial({ color: 0x909090 })
)
obj2Mesh.position.z = - distance
scene.add(obj2Mesh)

const obj2Group = new THREE.Group()
obj2Group.add(obj2Mesh)
scene.add(obj2Group)

function configureObj2PositionHorizontally(angleInDegree: number) {
  const radianAngle = angleInDegree * oneDegreeInRadians;

  obj2Group.rotateY(radianAngle)
}

function configureObj2PositionVertically(angleInDegree: number) {
  const radianAngle = angleInDegree * oneDegreeInRadians;

  obj2Group.rotateX(radianAngle)
}

If you wish to move Obj1 while still having Obj2 orbit around it, you can create another group that includes both obj1Mesh and obj2Group, and then move this new group accordingly:

const mainGroup = new THREE.Group()
mainGroup.add(obj1Mesh, obj2Group)
mainGroup.translateX(2)
scene.add(mainGroup)

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

Tips for implementing arraybuffer playback in video tags

I have been exploring ways to convert images from an HTML canvas into a video. After much research, I just want to be able to select a few images and turn them into a video. By passing multiple images to a library engine, I am able to receive an array buff ...

React application no longer displaying content following the upgrade to React 18 version

My React App was functioning perfectly, but after updating to React 18, MUI v5, and Redux v5, it stopped rendering anything. When I check the terminal, it shows: "webpack compiled successfully" However, in the Chrome console, I see: Warning: In ...

Selenium - Tips for entering text in a dynamically generated text field using Javascript!

I'm fairly new to the world of web scraping and browser automation, so any guidance would be greatly appreciated! Using Python's Selenium package, my objective is: Navigate to Login using the provided username & password Complete my order thr ...

Exploring the Potential of Mobile Development using AngularJS

I am in the process of creating an app with the following key design objectives: Efficiency and modularity - a light core that can be expanded to create a feature-rich app in a cohesive manner Mobile focus - this app is primarily aimed at mobile platform ...

Discover the best method for summing all values within a JSON object that contains multiple unique keys

What is the best way to sum up all values in a JSON object? The object provided below contains values that are in string format and it has different keys. var numbers = { x: "4", y: "6", z: "2" }; The result should be: total ...

How can data on the server be fetched using an AJAX request in Express.JS and displayed on the client side?

I have been given the task of displaying this code on the client side. I've successfully loaded data/content on the page but it lacks a certain level of elegance. var express = require('express'); router = express.Router(), ...

Error message: Unable to iterate through a non-iterable object in React reducer

I find myself in a unique predicament and could use some assistance. userData : { isValidCheckup: true, accounts: { userAccount: [ { accountType: 'checkings', includeInCheckup: false }, { accountType: 'check ...

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

npm is facing difficulties while trying to install the scrypt package. It is prompting the requirement

When attempting to run a blockchain application, I encountered an error message that reads: npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] install: node-gyp rebuild npm ERR! Exit status 1 npm E ...

What is the maximum number of requests that Node-Express can send simultaneously?

Currently, I am facing a challenge with my script that involves fetching 25,000 records from AWS Athena, a PrestoDB Relational SQL Database. For each of these records, I need to make a request to Athena and then another request to my Redis Cluster once the ...

JavaScript: Navigating Through Frames and iFrames in Internet Explorer

Is there a way to run JavaScript code after my iFrames or Frames have finished loading? It seems like document.onReady fires before the frames are actually displayed on the page. Any ideas on how to make this work? I came across a plugin called FrameReady ...

Steer clear of manually inputting URLs in your React components

As I embark on my journey with Gatsby, I am noticing a recurring pattern in my code. A prime example is when creating links, where I often find myself doing something like this: import {kebabCase} from "lodash"; // ... <Link to={`tags/${kebabCase( ...

Managing an Angular timer: Starting and resetting it via the controller

Is there a way to start a timer when the user clicks on the recordLogs method and reset the timer when the user clicks on the stopLogs method? According to the angular-timer documentation, we should be able to use the timer-stop and timer-clear methods to ...

Error: Express is undefined and does not have a property called 'use'

I'm encountering a problem with my express server specifically when I utilize the 'app.use' command. Within my task-routes.js file, the following code is present: import express from 'express'; const router = express.Router(); ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

When using iOS, inserting an iFrame with a source URL (SRC) on a webpage will automatically open the URL

Currently facing a peculiar issue within a Cordova app, specifically on iOS. The scenario is: I have an HTML page with existing content. At a later stage, I fetch additional HTML from a remote source and inject it into the original HTML page. However, whe ...

Failure in rendering components with React and ElectronThe issue of rendering components with

As a newbie to the world of React and Electron, I have been experimenting with separating my components into different JSX files and importing them to render in div tags within my index page for an Electron app. However, I'm facing some confusion as i ...