Using three.js to showcase a sequence of various objects consecutively

I am currently working with three.js to create mesh and textures for 20 different objects. Below, you will find an example object.

My goal is to display each of these 20 objects sequentially on the screen. I want to show the first object, have it stay on the screen for a brief moment (approximately 0.5 seconds), then turn it off and display the next object in line. The timing between displaying the objects is crucial for me. How can I achieve this?

To start, I am adding all the meshes to an array:

for ( var i = 0; i < count; i ++ ) {

    geometry = // new geometry ... 
    material = // new material ...
    //the lines above are unnecessary
    var mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);
    objects.push(mesh);
  
}

Here is the section related to rendering:

The render function is as follows:

function render() {
requestAnimationFrame(render);</p>
for ( var i = 0; i < count; i ++ ) {
    
        var mesh = objects[ i ];
    
    }

renderer.render(scene, camera);

}

As previously mentioned, after showing the first object for 0.5 seconds, I need to turn it off and display the next object. However, I'm having trouble finding a solution. What steps should I take?

Answer №1

To achieve the desired result, you can utilize the following code snippet:

let idx = Math.floor(seconds/500) % models.length;

Here is a complete illustration of how this works in action:

const renderer = new THREE.WebGLRenderer({antialias:true});
document.body.appendChild(renderer.domElement);

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 10);
camera.position.setScalar(1.3);
camera.lookAt(scene.position);

const material = new THREE.MeshNormalMaterial();

const models = [
  new THREE.BoxGeometry(),
  new THREE.SphereGeometry(),
  new THREE.CylinderGeometry(),
  new THREE.ConeGeometry(),
  new THREE.IcosahedronGeometry(),
  new THREE.OctahedronGeometry(),
  new THREE.TorusGeometry(),
  new THREE.TorusKnotGeometry(),
  new THREE.DodecahedronGeometry(),
].map(geometry => new THREE.Mesh( geometry, material ));

let currentIndex = null;

requestAnimationFrame(function render(seconds) {

    if (renderer.width !== innerWidth || renderer.height !== innerHeight){
      renderer.setSize(innerWidth, innerHeight);
      camera.aspect = innerWidth/innerHeight;
      camera.updateProjectionMatrix();
    }

    const index = Math.floor(seconds/500) % models.length;
    if (currentIndex !== index) {
      scene.remove(models[currentIndex]);
      scene.add(models[index])
      currentIndex = index;
    }

    scene.rotation.y += 0.01;

    renderer.render(scene, camera);
    requestAnimationFrame(render);
});
body { margin: 0; overflow:hidden}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/107/three.min.js"></script>

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

Guide on integrating a jQuery method for validating a value using regular expressions

I'm currently using the Jquery validation plugin to validate form fields. One of the fields I am validating is for academic years, which should be in the format of 2013-2014. To achieve this validation, I have created a custom Jquery method as shown b ...

Encountering crashes when trying to map JSON data onto React components

I have created a menu items application that displays products from a JSON file. When an item is clicked, it shows some modifiers for that item. Everything works well until certain categories or items are clicked, causing the application to crash. To test ...

Constantly showing false values in AngularJS Firebase array objects

Encountering an issue with retrieving data from Firebase. When viewing console.log($scope.statusbaca), it shows 2 queries, true and false. However, in the app it only displays false. Apologies for any language barriers as English is not my first language. ...

Ways to trigger javascript following each ajax or complete request

I have a jQuery function that attaches a click event to specific elements, as shown below. $(".alert-message .close").click(function(e) { $(this).parent().fadeTo(200, 0, function() { $(this).slideUp(300); }); e.preventDefault(); }) ...

What could possibly be causing the notification to fail to function in my deferred scenario?

I'm currently delving into the world of jquery deferred and making good progress, but I have encountered a hurdle when it comes to the notify feature. In my code snippet, you will notice that I attempted to use the notify method, only to find out that ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

Encountering a Basic React Issue: Unable to Implement @material-ui/picker in Next.js

I'm currently attempting to integrate the @material-ui/pickers library into my Next.js application. In order to incorporate the Picker provider, I followed the guidance provided in the Next.js documentation by adding the _app.js file inside /pages: i ...

Prepare for a thorough cross-referencing session

In my attempt to create a tool with 3 inputs that are interdependent - "Earn %", "Earn $" and "Own Price". Initially, the default value for "Earn percentage" is set at "10", making the initial calculation function as intended. Changing this one value auto ...

The problem of having an undefined state in Vuex arises

https://i.stack.imgur.com/52fBK.png https://i.stack.imgur.com/GcJYH.jpg There is an error occurring: TypeError: Cannot read property 'state' of undefined ...

Transferring data securely via URLs

I need advice on securing a JavaScript function that passes values into URLs in order to navigate to another page. What precautions should I implement to prevent manipulation of this process? This is the code snippet I am currently using: window.location ...

The information displayed in my Google snippet does not match the content of the intended URL

It may seem a bit confusing, so to clarify, here is an example: When you click the +1 button on this page, the snippet will display the text and URL from that specific page. However, in my case, the snippet displays text from the homepage URL instea ...

What could be the reason behind the failure of this computed property to update in my Vue 3 application?

As I transition from Vue's Options API to the Composition API, I decided to create a small Todo App for practice. Within App.vue, my code looks like this: <template> <div id="app"> <ErrorMessage v-if="!isVali ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

Swapping out the default JavaScript random number generator for my custom JSON-based solution

I've been working on creating a D3 graph to display my data. After following a tutorial, I arrived at this particular piece of code: // 8. An array of objects of length N. Each object has key -> value pair, the key being "y" and the value is a r ...

Utilizing jQuery for animating SVG elements with dynamic color changes and scaling effects upon hover

Seeking assistance from coding experts! I have created an icon and am attempting to modify it so that the color changes when hovered over. Additionally, I want the white square to scale down by 50% starting from the top-left corner of its current position. ...

Ensuring Package Security in NodeJS and NPM

Given the immense popularity of NodeJS and how NPM operates, what measures can be taken to prevent the installation of insecure or malware-laden packages? Relying solely on user feedback from sources like StackOverflow or personal blogs seems to leave a si ...

Troubleshooting the Issue of Angular Model Not Refreshing in Angular.js

Running into an issue with my directive where the model isn't updating as expected. Here's a snippet of my HTML code: <div class="text-area-container"> <textarea ng-model="chatText" ng-keyup="updateCount(chatText)">< ...

Deleting an item from an array using Mongoose

Looking to eliminate an element from an array in a document using mongoose. Example entry: { _id: "12345", folder: { name: "Folder1", files: [ { fileName: "File 1", fileID: "6789", folderID: "12345" } ] ...

Issue: Using the useParams() hook triggers a TypeError, stating that useContext(...) is undefined

Having trouble with the useParams() react hook to fetch a parameter, and encountering this error: Error: useContext(...) is undefined The hooks file throws this error on line 40: /modules/hooks.js:40 39 | > 40 | const match = useContext(Context) ...

What steps should I follow to delete or modify an anchor that has been inserted using the appendAnchor

While working with ammo.js and ThreeJS, I have been trying to find a way to remove or modify a softbody anchor that was added using the clothSoftBody.appendAnchor method. Although I have searched within the get_m_cfg and set_m_cfg functions for clothSoftBo ...