Rotation of objects using Three.js on a spherical surface

I have successfully implemented a particle system to evenly distribute points on a sphere and then place instances of a given geometry on those points. Now, I am looking to rotate those geometries to match the surface angle of the sphere.

Below is the current function:

function placeGeometryAtPlatonicPoints (points) {
  var len = points.length -1,
    x, y, z,
    geometry,
    // subgroup a group to apply the rotations to
    subgroup = new THREE.Object3D(),
    mesh,
    material = new THREE.MeshLambertMaterial({
      color: 0x0992299
    }),
    r,
    theta,
    varphi;

  // I wait to append this group because I am waiting for the 
  // particles to settle into there positions
  scene.add(group);

  for (len; len >= 0; len -= 1) {
    // Geometry could be any geometry I am just using a cube to test.
    geometry = new THREE.CubeGeometry(25, 25, 25, 1, 1, 1);
    x = points[len].x;
    y = points[len].y;
    z = points[len].z;

    // Move the geometry to the point on the sphere. 
    geometry.applyMatrix(new THREE.Matrix4().makeTranslation(x, y, z));

    mesh = new THREE.Mesh(geometry, material);
    subgroup.add(mesh);

    r = Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2));
    theta = Math.acos(z/r);
    varphi = Math.atan(y/x);

    theta = theta * (180/Math.PI);
    varphi = varphi * (180/Math.PI);

    console.log({
      theta : theta,
      varphi : varphi
    });

    subgroup.rotation.x = 0;
    subgroup.rotation.y = 0;
    subgroup.rotation.z = 0;

    group.add(subgroup);
  }
}

I am still learning Three js, so if there is a more efficient way to achieve this, please share your suggestions. You can view my work in progress here. The animation might take a moment to place the particles correctly before rendering the geometry, but I enjoy the visual effect.

Answer №1

To achieve cubes that are perfectly tangent to a sphere, imagine each cube as if it's attached to the end of a stick.

Visualize the stick as an Object3D positioned at the center. The cube is connected to the stick at coordinates ( 0, 0, r ). Proceed to rotate the stick to your desired position, avoiding the poles along the way.

var parent = new THREE.Object3D();
scene.add( parent );

var stick = new THREE.Object3D();
var point = new THREE.Vector3( x, y, z );
stick.lookAt( point );
parent.add( stick );

var geometry = new THREE.CubeGeometry( 25, 25, 25, 1, 1, 1 );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.set( 0, 0, r );
stick.add( mesh );

Using three.js r.64

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

Assign a Value to a Hidden Input Type When a User Submits a Form

I have a straightforward form set up in the following code. I am looking to add the value entered in the rm_accounts text box to the hidden page_confirm input value at the end of the URL. I hope that explanation is clear. In simple terms, if the user type ...

Using ng-repeat with an AJAX-called JSON is not possible

I've been struggling with handling JSON data from an AJAX call and displaying it using ng-repeat. If you want to take a look at my code in a more organized way, I've shared it on http://jsfiddle.net/7quj9omw/. However, please note that the code ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

The perpetual cycle of redirection through middleware

Implementing straightforward middleware logic and encountering Encountered an infinite redirection in a navigation guard when transitioning from "/" to "/login". Halting to prevent a Stack Overflow. This issue will cause problems in p ...

Utilizing the props value for emission within the emits array: A guide

While attempting to list a custom event in the component's emits option, I encountered a console error. The code looked like this: PARENT <Btn event-name="toggleSideMenu" @toggle-side-menu="toggleHandler"> togg ...

Creating a multi-dimensional array in JavaScript with two different sizes

I'm struggling to find the best way to create a multi-dimensional array with varying sizes dynamically. Our user interface requires a pattern where there are rows of 4 items followed by rows of 3 items. This pattern should continue until all contents ...

Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

I'm new to AngularJS and I've encountered a challenge that requires an elegant solution. My application receives a list from the server, which is used as the data source for the select tag's options. Let's assume this list represents a ...

Using the power of jQuery to load Ajax content, unfortunately, the content remains

Hey there, I'm currently working with an HTML file that utilizes AJAX to load content from other HTML files on the same server. However, for some reason, it's not functioning properly. I'm new to AJAX and I'm not sure what could be caus ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...

Clicking on a JQuery element triggers an AJAX function, although the outcome is not aligned with the intended

Instead of using a fiddle for this task, I decided to work on it online since my knowledge of fiddles is limited. However, after multiple attempts and hours spent rewriting the code, I still can't get it right. The issue at hand requires that when cl ...

It seems like I'm having trouble sharing a collection of objects

Hey there, here's where I currently stand. I've got some code that sends an array of items to a .NET WebAPI (c#). var stuff = []; $('#items').find('input').each(function(){ var text = $(this).val(); stuff.push({ ID: ...

What is the best way to ensure that the search box automatically adjusts its position and size regardless of the screen resolution?

I'm currently working on a responsive website project and facing an issue with the absolute positioning of the search bar on the main page, which is crucial for me. Below is the code snippet: <div class="span4"> <form class="well form ...

Retrieving information using getStaticProps

I'm currently working on a new function that pulls data from The Guardian API, but I've hit a roadblock with an error message. Below is the response that's being returned: https://i.sstatic.net/90OoB.png Furthermore, presented here is the c ...

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...

Using jquery to dynamically change audio source on click

Is there a way to dynamically change the audio src using jquery? <audio id="audio" controls="" > <source src="" type="audio/mpeg" /> </audio> <ul id="playlist"> <?php if($lists) { foreach ($lists as $list) { ?> ...

Retrieving values from a multidimensional array in JavaScript

I need some help with my code. I am struggling to pass an array (larray3) containing elements from two other arrays (larray1 and larray2) from data.js to model.js and view.js. Despite correctly building the multidimensional array in data.js, when I receive ...

Deleting an item using jQuery

In the Document Object Model (DOM), there is a button available to remove the parent element here: <i class="fa fa-times remove-product-compare" aria-hidden="true"></i> Here is an example of my DOM structure: <div class="col-lg-12 col-md- ...

Experiencing Challenges with JavaScript Implementation Within an HTML Document

Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-3.3.1.js"> </script> <script type="text/javascript"> $(function() { alert("Hello World"); }); </script> <meta charset ...

Adjusting canvas size to match content dimensions

I posed a similar inquiry and it was categorized as a duplicate even though the suggested duplicate did not provide an answer to my question. Edit: The purported duplicate was [stackoverflow.com/questions/17211920/make-canvas-height-auto][1] I am utilizi ...