Managing objects over time in Three.js

I am looking to dynamically add and remove objects in a continuous stream. Imagine having an array of 50 objects, and I want to cycle through them with a period, essentially creating an object stream. I initially attempted using setTimeout and setInterval functions, but unfortunately, they did not yield the desired results both inside and outside the render function. So, I experimented with the following approach:

function render(){
    controls.update(clock.getDelta());
    renderer.render( scene, camera);
    i = i+1;
    if (i % 2 == 0){
        if (i % 300 == 0){
            remove(lights);
        }
        else
        {   scene.add(lights[(i/2)]);
        }
    }
}

While this code does work, it does not initiate the adding process with the first object. I also attempted utilizing getElapsedTime() instead of iterating through i, but unfortunately, it only added the initial object. Are there any more efficient time-controlled methods that I can utilize for this task?

Thank you in advance.

Answer №1

Here is a snippet of code that demonstrates how to achieve the desired functionality:

let toggleLights = true;
window.setInterval(function(){toggle()}, milliseconds);

function toggle() {
    let index;
    if(toggleLights) {
        for(index = 0; index < lights.length; ++index) {
            scene.add(lights[index]);
        }
    } else {
        for(index = 0; index < lights.length; ++index) {
            scene.remove(lights[index]);
        }
    }
    toggleLights = !toggleLights;
}

function render() {
    renderer.render(scene, camera);
}

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

Working with JSON data in JavaScript is proving to be challenging

Here is a json encoded result: { "result":[ { "CODE":"STC\/R\/935", "WAY":"In", "DATE":"2016-02-19", "TYPE":"Re-Entry", "TKTP":"NA", "TIME":"2016-02-23 17: ...

How can I navigate between pages without losing the data entered in the form fields

Is there a way in Ajax or jQuery to save form data and navigate between multiple form pages without using PHP Sessions? I want the form data to be saved until the user submits it, and when they do submit, all information from different pages should be in ...

JavaScript's prototype remains unique and is not duplicated

I've encountered an issue where my CoffeeScript classes are not properly copying the prototype. Here is the code snippet I am working with: module.exports = class ListQueue constructor: -> @queue = [] @queueIds =[] @currentId = 0 ...

The while loop is missing a value assignment for an integer

I am attempting to retrieve page number values from the method getPageNumber(), where the page number is being printed in the console. However, that value is not being used in the While loop. Even when I try to print pageNum, it returns a promise. Refer to ...

Transform the JSON data into a uniform structure by eliminating unnecessary information

Here is a snippet of JSON Data from Mongo : { "status": 1, "message": "", "data": [ { "_id": "5f489968a26b303c54d0a174", "name": "Mobile", "SubCategory": [ { "_id": ...

Discovering the Week by week commencement and conclusion dates utilizing angularjs

Previously, I was utilizing the angularjs-DatePicker from npm. With this plugin, I could easily select a date from the calendar. However, now I require two fields - FromDate and ToDate - to display the week StartDate and EndDate whenever a date within that ...

Tips for uploading a file to an Angular component and transmitting it through HTTP

Currently working on a project that involves the following files: app.component.html <div> <input type="file" ([ngModel])="file" accept="application/pdf" onChange="change()"> </div> app.module.ts: file: File = null; change(){ ...

An unanticipated SyntaxError was encountered while attempting to utilize an Ajax post, specifically in relation

I can't seem to figure out how to troubleshoot an ajax/jquery error. Here is the function I'm working with: var LogIn = { Email: $("#Name").val(), MobileNo: $("#txtMobileNumber").val(), PinCode: '', ...

Why is the Mongoose ObjectID causing issues when used as a parameter in a function?

Attempted passing a Mongoose ObjectID to a function using an onclick(). Below is the shortened code snippet: <a onclick="Like({{_id}}, {{likes}}, {{dislikes}});" class="btn btn-like"></a> <p id="{{_id}}"> {{likes}} likes </p> < ...

Determine the precise boundaries of the React component

I am working with a basic ellipse element: <span style={{ width: /*someWith*/, height: /*someHeight*/, borderRadius: "50%" }}/> and, I am using getBoundingClientRect() to retrieve its bounds (displayed in blue). https://i.ssta ...

Is it possible to simplify the use of two ng-shows and two dropdowns in AngularJS by utilizing just one dropdown

Is there a way to use a single dropdown that satisfies both conditions? <div ng-show="user == 'admin'"> <div class="col-md-8 col-sm-12 col-xs-12"> <select ng-model="li" > <option ng-repeat="li ...

By clicking, dynamically add unique classes along with incrementing numerical values

I have a span tag and a button tag <span class="myspan">1</span> <button id="add">Add +1</button> var arr=["myspan1","myspan2","myspan3","myspan4"} In order to add more span tags with new classes from the array and increase the v ...

"Enhance Your Smart Contract Interaction with Algrand's Method Calling

Currently, I am working on integrating an Algorand smart contract with a Next.js application. To sign transactions, I am utilizing Pera wallet. However, I have encountered an issue when attempting to call methods from the contract on the front end using th ...

One beneficial aspect of utilizing JavaScript closures for events is when defining a click event

There are two common ways to write code in JavaScript that accomplish the same task: Option A. SomeObject.prototype.hideElement = function(e, element){ e.stopPropagation(); hide(element); } Option B. SomeObject.prototype.hideElement = function( ...

Generating a JSON tree hierarchy from an array of nested objects

I have a JSON array of objects that looks like this: [{ "vehicleid": 3, "name": "Teste2VDD", "brand": "Scania", "model": "6x2", "class": "class1", "region": "Curitiba", "customer": "Cliente A", "customerid": 1 }, { "veh ...

Utilizing the navigator object in React Navigator and expo to enhance component functionality

My React Native application requires a redirection on a specific component. Within my main App.js component, I have the following code snippet: import React from "react"; import { Text } from "react-native"; import { createAppContainer } from "react-nav ...

Suggestions for changing sub-component data in Vue

I have a scenario where I am using a component with tabs inside. The Head component (parent) includes the following code: <v-btn @click="setSelectedTab('Set') "> ... <component :is="selectedTab"></component> ...

Showing information from a database while incorporating line breaks with the help of nl2br

Having trouble with the previous question, so I'll provide more detail here. Below is my index.php file where I explain the method used to save data to a database. <html> <head> <script> function updategroup() { var update_c ...

What techniques does Google use to craft mobile-friendly fixed backgrounds and parallax content within iframes?

Currently, I am working on a test that involves utilizing an intersectionobserver in conjunction with iframe postMessage to adjust the background image in a translate3d manner within the iframe. However, this method is causing significant jitter and potent ...

Sending Data Through Button from navBar in React-Native-Router-Flux

I have been working on a project that utilizes `react-native-router-flux` and I am facing a challenge in passing an object through `props`. Typically, I would use `Actions.someKey({ someProp: object })` for navigation. However, in this case, I need to navi ...