Guide on generating a unique X and Y rotation for every object created randomly in Three JS

I've been working on a personal project using Three JS as my main 3D object renderer. I'm trying to randomly generate spheres at various x, y, and z coordinates within a specified range. I was able to achieve this, but now I want each of these objects to have a random rotation speed along the x, y, and z axes ranging from -0.005 to 0.005. I'm unsure how to approach this and would greatly appreciate any help. Here is my code for random generation and animating 3D objects:

function randomStar(){
  const geometry = new THREE.SphereGeometry(0.25, 24, 24);
  const starMaterial = new THREE.MeshBasicMaterial({color: 0xffffff, wireframe: false});
  const star = new THREE.Mesh(geometry, starMaterial);

  const [x,y,z] = Array(3).fill().map(() => THREE.MathUtils.randFloatSpread(150));
  star.position.set(x,y,z);
  star.rotation.x += 0.01;
  star.rotation.y += 0.01;
  scene.add(star);
}
Array(350).fill().forEach(randomStar);

function animate() {
    requestAnimationFrame( animate );
  
    torus.rotation.y += 0.005;
    torus.rotation.x += 0.005

    torusOne.rotation.x += 0.002
    torusOne.rotation.y += 0.005;
    torusTwo.rotation.y+= 0.005;
    torusTwo.rotation.x += 0.002

    globe.rotation.y += 0.001
  
    renderer.render(scene, camera);
  }
  
   animate();

Answer №1

To bring some movement to your element, you can save a random rotation value when it's created and then animate it with each render.

star.userData.rx = Math.random() * 0.01 - 0.005;
star.userData.ry = Math.random() * 0.01 - 0.005;
star.userData.rz = Math.random() * 0.01 - 0.005;

...

animate() {
  star.rotation.x += star.userData.rx;
  star.rotation.y += star.userData.ry;
  star.rotation.z += star.userData.rz;
}

I've provided a CodePen example here:
https://codepen.io/cdeep/pen/OJjVXqW

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

Activate the saturation toggle when a key is pressed in JavaScript

I am trying to modify a script that currently toggles the value of a variable when a key is pressed and then lifted. Instead of changing the variable value, I would like to adjust the saturation of the screen based on key presses and releases. How can I ac ...

Utilizing multiple instances of Express in Node.js

I've been struggling to grasp how the Expressjs framework for Node.js manages routes across multiple files. In my main index.js file, the setup looks something like this: var express = require('express'); var app = express(); app.use(' ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

What is the best method for encrypting a URL that contains AngularJS data?

Here is the URL that needs to be encrypted: <a class="btn btn-success btn-sm btn-block" href="@Url.Action("myAction", "myController")?Id={{repeat.Id}}&HistoryId={{repeat.HistoryId}}" ng-cloak>View History</a> I am seeking guidance on enc ...

Leveraging Angular 2 for incorporating jQuery-based JavaScript ajax functionality

It seems like I'm attempting to force a square peg into a round hole as I work with Angular2 and Typescript. I've created a Javascript module that serves as an API client library for the API I'm utilizing. This library simplifies tasks such ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

Unexpected values being captured by Request.Form from Dynamic Textboxes

I am currently working with dynamic text boxes and retrieving their values in the code behind file. These text boxes are created using Javascript on my ASP.NET page. Here is a snippet of my code: <script type="text/javascript"> $(docume ...

Tips for passing multiple values with the same key in Axios as parameters

I need to develop a function that allows users to select multiple categories and subcategories, then send their corresponding ids as a query string using Axios. For example, if a user selects category IDs 1 and 2, along with subcategory IDs 31 and 65, the ...

A guide on incorporating a component from a nested directory with webpack

https://i.sstatic.net/kLB0S.png The directory structure above shows how my react app 'MyProject' is organized. Using this structure, I successfully utilize the Layout component in Main.jsx (located at src/Main.jsx) by : import Layout from &apo ...

JQuery is failing to properly return the string containing special characters like apostrophes

Storing the name "Uncle Bob's Organic" in the data-Iname attribute caused a retrieval issue, as it only retrieved up to "Uncle Bob". Here is the process used for retrieving the value from the data-Iname: var itemName = $(this).attr("data-Iname"); T ...

What is causing the while loop in Mongodb to repetitively insert the same document rather than cycling through the documents?

Currently, I am in the process of redesigning a MongoDB database structure where the reviews for a specific product will be integrated into the product document itself, rather than maintaining separate collections for products and reviews. I have created a ...

Displaying a list of JSON data in HTML using Angular.js is a breeze

I am attempting to create an HTML list displaying the id fields of game objects from a json file. However, it is not appearing in my user interface. I am unsure why it is not rendering properly. ---core.js--- var gameapp = angular.module('gameapp&ap ...

What are the steps to confirm form submission with $pristine and $dirty in Angular?

I recently created a form using the resources available at https://github.com/nimbly/angular-formly and . While most of the validation is being handled by Angular, the user-friendliness of the form validation needs improvement. I am looking to implement va ...

Hide the content within a table row by setting the display to

I need to hide the div with the id "NoveMeses" if all h3 elements display "N.A." Is there a way to achieve this? If both h3 elements in row1 and row2 contain the text "N.A.", I want the div NoveMeses to be hidden. Below is the code snippet using AngularJ ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...

Fixing the GLTF Loader Error in Vue JS: Troubleshooting the issue of 'No loaders configured'

I am attempting to integrate a gltf file into a Vue project. Below is the code I have been working on: import * as THREE from 'three' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; let scene, camera, renderer; fu ...

Transforming an ES6 JSON object into a dictionary: a step-by-step guide

As someone who is new to learning ES6 and JQuery, please forgive me if this question has been asked before (I couldn't find similar ones). Currently, I am working on retrieving data from a JSON file in the following format: { EUR: { code: "EUR" ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

javascript context scope

As I delve into the world of JavaScript, please bear with me as I navigate through defining multiple namespaces. Here's an example of how I'm doing it: var name_Class = function(){ this.variable_name_1 = {} this.method_name_1 = function() { ...

Tips for customizing the color of the current date in the angular-material datepicker

I've created a function in angular-material to disable dates two days from now, but I'm struggling to change the color of the current date if it's disabled. The issue is that when the current date is disabled, it displays in a very light blu ...