How can I set the sphere's rotation in THREE.js to be absolute instead of cumulative?

I have encountered an issue with setting the rotation of a Three.js sphere to an absolute value. Whenever I use rotateY, the value I apply gets added or subtracted from the previous rotation instead of setting a new absolute rotation.

In a similar scenario involving a cube (Three.js Set absolute local rotation), changing cube.rotation.x = someValue achieves the absolute rotation that I am aiming for.

Unfortunately, the SphereGeometry object I am using (which has a world map texture) does not have a rotation attribute.

I could potentially keep track of past rotations and only apply the difference, but this approach might eventually lead to cumulative round-off errors.

Is there any alternative method to accomplish this? Perhaps a reset function of some sort?

  async orient(lon: number, lat: number): Promise<void> {
    if (Globe.mapFailed)
      throw new Error('Map not available');
    else if (!Globe.mapImage)
      await new Promise<void>((resolve, reject) => Globe.waitList.push({ resolve, reject }));

    if (!this.initialized) {
      this.camera = new PerspectiveCamera(FIELD_OF_VIEW, 1);
      this.scene = new Scene();
      this.globe = new SphereGeometry(GLOBE_RADIUS, 50, 50);

      const mesh = new Mesh(
        this.globe,
        new MeshBasicMaterial({
          map: new CanvasTexture(Globe.mapCanvas)
        })
      );

      this.renderer = new WebGLRenderer({ alpha: true });
      this.renderer.setSize(GLOBE_PIXEL_SIZE, GLOBE_PIXEL_SIZE);
      this.rendererHost.appendChild(this.renderer.domElement);
      this.scene.add(mesh);
      this.camera.position.z = VIEW_DISTANCE;
      this.camera.rotation.order = 'YXZ';
      this.initialized = true;
    }

    this.globe.rotateY(PI / 20); // Just a sample value I experimented with
    this.camera.rotation.z = (lat >= 0 ? PI : 0);
    requestAnimationFrame(() => this.renderer.render(this.scene, this.camera));
  }

Update:

As a temporary solution, I implemented the following workaround:

    this.globe.rotateX(-this.lat);
    this.globe.rotateY(this.lon);
    this.lon = to_radian(lon);
    this.lat = to_radian(lat);
    this.globe.rotateY(-this.lon);
    this.globe.rotateX(this.lat);

I am storing the previous rotations performed so that I can reverse them before applying new rotations. The conversion between degrees and radians, along with the need to reverse the sign of longitude rotation, make the process slightly complex.

Answer №1

It seems there may be some confusion between the functions geometry.rotateY(rot) and mesh.rotation.y = rot. According to the documentation:

.rotateY(): This function rotates the geometry around the Y axis, typically used as a one-time operation rather than during a loop. For real-time mesh rotation, it is recommended to use Object3D.rotation.

The geometry.rotateY(rot) function should only be used once because it updates all vertex positions, requiring iteration through each vertex to update. This is helpful when modifying the "original state" of the geometry, such as orienting a character model along the z-axis at the start.

On the other hand, mesh.rotation.y = rot; is more suitable for real-time rotations, leaving the intrinsic vertex positions untouched while rotating the entire mesh. For instance, when animating a character moving across a map.

this.mesh = new Mesh(geometry, material);

// Set rotation to an absolute value
this.mesh.rotation.y = Math.PI / 20;

// Increment rotation by a relative amount (such as per frame):
this.mesh.rotation.y += Math.PI / 20;

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

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

How can a false validation be conducted on knockout js?

Using knockout js, I have an input type checkbox and I want to trigger the "not true" action when this checkbox is selected. Here's what I have attempted: <input type="checkbox" data-bind="checked: !IsVisible"/> Unfortunately, this code isn&ap ...

What is the best way to conceal a section of a div using CSS/React?

I am attempting to create a design where the entire content of a div is displayed initially, and then after clicking a button labeled "show less", only 300px of the content will be shown with the button changing to "show more". <div className="bod ...

JavaScript: Choosing between explicit imports and the * sign

Why do this in one way: import * as copy from 'copy-to-clipboard'; instead of the other way: import { someMethod } from 'copy-to-clipboard'; Does it impact performance or bundle size? Personally, I find the second option cleaner. ...

Conditional statement in Javascript for document.cookie

I am attempting to create a basic if statement that relies on the value of a cookie. The function looks like this: function setHomePage() { if ($.cookie('settingOne') == 'jjj') { $('.secO').css('display', & ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Tips for ensuring the child directive has finished rendering before proceeding?

I am faced with a scenario where one directive is dependent on another: <div style="border:2px solid black;height:150px;padding:10px"> <my-internal-directive></my-internal-directive> <my-internal-directive></my-interna ...

Error connecting to Firebase Cloud Functions - connection issue

Whenever I call my cloud function, I see the following message in the logs: Function execution took 5910 ms, finished with status: 'connection error'. It seems to be related to promises and returning or !d.exists, but I haven't been able to ...

What is the process for retrieving the date and time a location was added to Google Maps?

My goal is to extract the date and time a location pin was added in Google Maps. For example, if I search for McDonald's in a specific area, I want to retrieve the dates and times of all McDonald's locations in that area. Is there a method to acc ...

Guide on assigning a value to a material ui select box

Currently, I am utilizing the material UI Select component for the year field in my project. What I aim to achieve is setting a default year based on the value present in the state. To populate the years, I am using an array of years. Here is the method r ...

Guide to adding an image with feathers.js and multer:

I am currently working on integrating feathers.js with React for my project and I am facing an issue with uploading images. I have tried using multer and busboy for handling the upload, but I am unable to successfully upload the image or access it through ...

Compiling TypeScript to JavaScript with Intellij IDEA while preserving the folder hierarchy

Seeking assistance with maintaining directory structure when compiling Typescript to Javascript in Intellij Idea. The current directory setup is as follows: root - ts - SomeClass1.ts - SomeFolder - AwesomeClass2.ts - tsc The desired compiled file ...

Is it possible to incorporate multiple searchBoxes on my website using the Google Maps API?

I am currently working on creating an origin and destination menu for users to select locations in each input. The goal is to add a marker to the map for each input and then calculate the distance between them. So far, I have successfully added a map with ...

Controlling dropdown menus filled with AJAX responseData

When it comes to Javascript, JQuery has always been a reliable companion for me. However, there are instances where I encounter challenges that require some extra effort to overcome. Today happens to be one of those days. I've stumbled upon an issue t ...

Tips on adding an image using Reactjs

I am currently working in Reactjs with the Next.js framework. I am attempting to upload images using Axios (POST method API) and will be utilizing an "api in PHP". Could someone please guide me on how to achieve this? I have tried the code below, but it&ap ...

Ensure the header remains fixed when scrolling in an HTML page with Bootstrap

I created the following code. However, when I scroll down the table, the header disappears from view. I would like the header to always remain at the top, even when scrolling. Despite searching Google multiple times and trying various solutions, I have no ...

The Ajax data was not displayed in the console log, instead an error message was returned stating "http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found"

I am attempting to make a dropdown option dependent on another using ajax. I want to view the data in the console to see if it is successful or not. I expect the data to be displayed in the console log, but instead, an error is being given. http://local ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

Swap the content of one div with another div using client-side code only

Currently, I am in the process of developing my personal website. To enhance user experience, I have implemented a vertical navigation bar on the left side of the page. My goal is to replace the content of a specific div with content from other HTML files ...