Creating a simulation of a sun-like vector rotating around a sphere in three.js

Currently, I am attempting to modify this code (which was originally based on an implementation found here). While I have successfully achieved the desired visualization and rendering effects, my goal now is to introduce realistic movement into the animation.

The location of the light source is determined by a normalized vector (e.g. THREE.Vector3(1, 0.75, 0), giving the appearance that the light is shining from the top right corner). My next step involves rotating this vector around the sphere in a manner that simulates the sphere orbiting the light source. However, I have encountered difficulties in calculating the appropriate values for the next set of x, y, z coordinates. Various attempts were made, including adjustments to the position of the vector, as well as the application of Euler angles and rotational matrices:

euler = new THREE.Euler(f,g,h, 'XYZ');
matrix = new THREE.Matrix4().makeRotationFromEuler(euler);
light = vector.applyMatrix4(matrix);

Despite these efforts, uncertainties linger regarding how to determine the correct values for f, g, h that would prevent erratic movements of the light around the sphere.

Would you say that I'm heading in the right direction?

You can view a demonstration of the current setup here: http://jsfiddle.net/VsWb9/3890/

Answer №1

There is an issue with increasing two of the 3 coordinates in euler angles in a linear manner.

When dealing with rotations that are not around the x/y/z axis, it is recommended to use quaternions for better understanding, avoiding issues, coding efficiently, and reducing computational cost.

Quaternions are quite intuitive, especially in threejs. They consist of 4 coordinates: 3 for the rotation axis and the fourth for the rotation value.

var quat = new THREE.Quaternion();

// Define the axis for rotation (must be normalized)
var axis = new THREE.Vector3(0,1,0).normalize();
// Specify the angle value in radians
var angle = 0;

// Set the original position of the light vector
var light = new THREE.Vector3(1,0,0).normalize();

In your render loop, update the angle value and instruct the quaternion to use the specified axis and angle:

angle += .001; // (or angle -= if the axis points in the +y direction like in this case)
quat.setFromAxisAngle(axis, angle);

Finally, apply the quaternion:

light.applyQuaternion(quat);

Here is the updated fiddle link: http://jsfiddle.net/Atrahasis/0v93p2xy/


Important note on normalized vectors:

  • A normalized vector has a length of 1 unit.
  • Vectors like (1, 0, 0), (0, 1, 0), and (0, 0, 1) are already normalized (unit vectors).
  • A vector such as (1, .75, 0) is not normalized; its length is calculated using Pythagorean theorem as √(1² + .75²) = 1.5625.
  • For instance, (0.6614..., .75, 0) is a normalized vector.

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

Is it possible to request a GET on a server's JSON file using a specific key?

I am currently working on a project involving an auto-suggestion exercise using a JSON file located on a server. I'm not entirely clear on the web development terminology, so one requirement has me a bit confused: The requirement states: "On the keyu ...

Troubleshooting issue with Bootstrap's responsive scrollspy functionality

I am experiencing an issue with the responsiveness of my page. When I reduce the width of the page to half, the scrollspy disappears unexpectedly. I am unsure about the root cause of this problem. If you run the code I have shared here, you can observe th ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

Display real-time information in angular material table segment by segment

I need to incorporate service data into an Angular mat table with specific conditions as outlined below: If the difference between the start date and end date is less than 21 days, display 'dd/mm' between the 'start_date' and 'end ...

Adding JQuery to a running webpage using the DOM and Opera browser add-ons

I'm currently working on an Opera Extension and I have a question. Is there a way to use the includes folder in order to directly inject jQuery into the live HTML of a webpage? For example, can I change the background color of the DOM to black? If ...

Consider creating a distinct document for your "scripts"

Within my package.json configuration file, the "scripts" section contains numerous commands structured as shown below. "scripts" { "script1": "command example", "script2": "command example", "script3": "command example", "script4": "command exampl ...

Challenges related to streaming processes and uploading to S3 cloud storage

Encountering difficulties with a zero byte stream. Currently, I am resizing an image and sending it as a stream to S3. Initially, when I connect the output to the response, it displays properly. // To retrieve the file remotely var request = http.get(&apo ...

Reorder div elements using jQuery with two specific criteria

On my website, I have implemented a method for sorting divs (.ligne) with different sorting options: by name, date, status, and type. The jQuery code I've written works well, but I want to refine it further to make it lighter. When clicking on each h ...

Facing issue with local redis session not functioning as intended

I'm encountering an issue with my redis session not functioning properly when testing locally. EDIT: Additionally, I realized that it's failing to save a cookie when trying to set req.session[somekey] as undefined like so: req.session.user = u ...

Can firebase and express be integrated seamlessly?

I'm a newcomer to Express and I want to create a REST API with express.js that utilizes Firebase as its database. Can these two technologies actually work together? Here is the code snippet I tried: cons ...

Trigger a popup alert when a Bootstrap select live search is clicked

<select class="selectpicker form-control" data-live-search="true" name = "name1" id ="id1"> <option>Option1</option> <option>Option1</option> <option>Option1</option> <option>Option1</option> ...

Conceal a text field depending on the value within a hidden field that was populated automatically by a JavaScript function

I encountered a peculiar issue recently. I have a form with a field for entering card numbers. There is a JavaScript code that automatically detects the type of card (such as Maestro, Visa, etc.) based on the entered number. If the detected card type is &a ...

Enveloping elements with jQuery

I am currently utilizing AJAX with jQuery to retrieve some HTML content, and here is the success function: function handleSuccess(response) { var searchTerm = $("#input").val(); // Convert string of HTML to object var anchors = $('<d ...

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

How can the table attribute "name" be obtained and added as the file name for DataTables in the export feature?

Having multiple tables on my page using JQuery DataTables, I find it to be a useful library. I am looking to modify the file name for exporting the data on these tables. I have several DataTables on this page This is how I initialize my tables: $(docume ...

Is there a way to access the values that have been dynamically updated by JavaScript

Is it possible to parse an HTML page using the org.w3c.dom package? For example, let's take a look at . This webpage contains a counter that is updated by JavaScript. However, when trying to retrieve a value from: <div class='counter_field&ap ...

Calculate the number of rows in a table that contain identical values

I have a puzzling issue that has been on my mind. I currently have an SQL statement that selects specific rows from my database and displays them in an HTML table, which is functioning properly. However, I now need to determine how many rows have the same ...

Creating a dynamic variable within a for loop and calculating the total of values to assign to that variable

Is it possible to dynamically create variables and add values to them repeatedly? For example: var totalIncomeCr = 0, totalIncomeDr = 0; for (var k = 1; k <= numOfYears; k++) { if(response[i]["AmountType" + k] == "Cr") { if(response[ ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...