Animating the scale of multiple objects in Three.js allows for dynamic and engaging visual

Hi there! I am new to three.js and currently going through various tutorials to master the art of animating 3D objects using three.js. As a result, you may find some parts of the code below to be familiar.

My objective: I am looking for a way to gradually change the scale of each object within a loop over a specified time period (3 to 5 seconds). Ideally, I would like these objects to not only change in size but also potentially in shape.

Here is what I currently have:

var Decoration = function() {

    // Invoke the Group constructor with the given arguments
    THREE.Group.apply(this, arguments);

    this.rotationSpeed = Math.random() * 0.01 + .001 + .001;
    this.rotationPosition = Math.random() * 0.01 + .001 + .001;
    this.scale = Math.random() * 0.21 + .051 + .021;

    this.rotation.x += 0.01;
    this.rotation.y += 0.02;
    this.scale.x += 1;  
    this.scale.y += 1;  
    this.scale.z = 1;  

    // Assign a random color
    var colors = ['#ff0051', '#f56762','#a53c6c','#f19fa0','#72bdbf','#47689b'];

    // The main bauble is an Octahedron
    var bauble = new THREE.Mesh(
        addNoise(new THREE.OctahedronGeometry(15,0), 0),
        new THREE.MeshStandardMaterial( {
            color: colors[Math.floor(Math.random()*colors.length)],
            shading: THREE.FlatShading ,
            metalness: 0,
            roughness: 0.8,
            refractionRatio: 0.25
    } )
    );
    bauble.castShadow = true;
    bauble.receiveShadow = true;
    bauble.rotateZ(Math.random()*Math.PI*2);
    bauble.rotateY(Math.random()*Math.PI*2);
    this.add(bauble);

};
Decoration.prototype = Object.create(THREE.Group.prototype);
Decoration.prototype.constructor = Decoration;
Decoration.prototype.updatePosition = function() {
    this.rotationPosition += this.rotationSpeed;
    this.rotation.y = (Math.sin(this.rotationPosition));
};

var clock = new THREE.Clock();


// Create a scene which will hold all our meshes to be rendered
var scene = new THREE.Scene();

// Create and position a camera
var camera = new THREE.PerspectiveCamera(
    60,                                   // Field of view
    window.innerWidth/window.innerHeight, // Aspect ratio
    0.1,                                  // Near clipping pane
    1000                                  // Far clipping pane
);

// Reposition the camera
camera.position.set(0,30,50);

// Point the camera at a given coordinate
camera.lookAt(new THREE.Vector3(0,15,0))

// Create a renderer
var renderer = new THREE.WebGLRenderer({ antialias: true });

// Size should be the same as the window
renderer.setSize( window.innerWidth, window.innerHeight );

// Set a near white clear color (default is black)
renderer.setClearColor( 0xfff6e6 );

// Append to the document
document.body.appendChild( renderer.domElement );


var decorations = [];

// Add some new instances of our decoration
var decoration1 = new Decoration();
decoration1.position.y += 10;
scene.add(decoration1);
decorations.push(decoration1);

var decoration2 = new Decoration();
decoration2.position.set(20,15,-10);
decoration2.scale.set(.8,.8,.8);
scene.add(decoration2);
decorations.push(decoration2);

var decoration3 = new Decoration();
decoration3.position.set(20,10,-10);
scene.add(decoration3);
decorations.push(decoration3);

var decoration4 = new Decoration();
decoration3.position.set(20,10,-10);
scene.add(decoration4);
decorations.push(decoration4);

// Render the scene/camera combination
renderer.render(scene, camera);

requestAnimationFrame(render);

function render() {

    controls.update();

var t = clock.getElapsedTime();
    
    if (t >= 3.0)
    {
        clock = new THREE.Clock();
        this.scale.set(1,1,1);
    }
    else
    {
    this.scale.x = 1-(t/3.0);
    this.scale.y = 1-(t/3.0);
this.scale.z = 1-(t/3.0);   
    }

    // Update the decoration positions
    for(var d = 0; d < decorations.length; d++) {
        decorations[d].updatePosition();
    }

    // Render the scene/camera combination
    renderer.render(scene, camera);

    // Repeat
    requestAnimationFrame(render);
}

If you have any suggestions or guidance, I would greatly appreciate it!! Thank you so much :)

Answer №1

In order to achieve the desired animation/render effect for any specified decoration element, the necessary steps need to be taken within the render function. By applying the transitions to the decoration elements within this function, it becomes possible to extend the effect to multiple variables.

Consider the following approach:

Begin by defining the clock variable:

var clock = new THREE.Clock();

Then, make adjustments to your render function as shown below:

function render() {

    for(var d = 0; d < decorations.length; d++) {
        decorations[d].rotation.x += 0.01;
        decorations[d].rotation.y += 0.01;
    }

    var t = clock.getElapsedTime();

    if (t >= 3.0)
    {
        clock = new THREE.Clock();
        // Update the decoration positions
        for(var d = 0; d < decorations.length; d++) {
            decorations[d].scale.set(1,1,1);
        }
    }
    else
    {
        // Update the decoration positions
        for(var d = 0; d < decorations.length; d++) {
            decorations[d].scale.x = 1-(t/3.0);
            decorations[d].scale.y = 1-(t/3.0);
            decorations[d].scale.z = 1-(t/3.0);
        }
    }

    // Render the scene/camera combination
    renderer.render(scene, camera);

    // Repeat the process
    requestAnimationFrame(render);
}

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

React's componentWillMount() does not support the use of "if" statements

I've been working on a component called "App" that includes a function componentWillMount. The purpose of this function is to redirect React Router when a certain condition is false. componentWillMount() { const isLoggedIn = session.getLogin() ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...

Use VueJS v-on:click and Vanilla JS to collapse various divs when clicked

Can VueJS and vanilla JS be used to collapse specific divs among many? I have information contained in separate card elements that include a title and a body. My goal is to make the body of each card expand or collapse when the respective title is clicked ...

Receive the complete HTML page as a response using JavaScript

When making an Ajax post to a specific page, I either expect to receive an ID as a response if everything goes smoothly, or I might get a random html page with a HTTP 400 error code in case of issues. In the event of an error, my goal is to open the enti ...

Maximizing Content Width in FullCalendar v5 to Ensure Screen Compatibility

As I develop a calendar and timeline view using fullcalendar v5, my clients are requesting a month view that displays the entire month without any scroll bars. While I am aware of setting the contentHeight to auto, there seems to be no option for adjusting ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Tips for successfully transferring data using a dynamic key in a Semantic UI Vue dropdown

My current challenge involves troubleshooting the semantic-ui-vue dropdown functionality. To view the issue, visit my sandbox link: https://codesandbox.io/s/3qknm52pm5. Within the sandbox environment, there are two dropdown menus labeled as From and To. ...

Are there any testing frameworks available for JavaScript that are similar to Junit and specifically designed for testing object-oriented JavaScript within Node

What are some recommended methods for testing object-oriented JavaScript in Node.js? For instance, let's consider the following Cat.js class: function Cat(age, name) { this.name = name || null; this.age = age || null; } Cat.prototype.getAge ...

Prevent the Spread of an Event for a Particular Controller

tl;dr Summary Develop a function that is able to handle a specific event on multiple elements within a hierarchy. The function should execute when the event is triggered on the first element reached during bubbling, but should not continue executing or re ...

Stopping Angular Route Alteration Depending on Routing Conditions

I have been searching everywhere for a solution to this issue. My goal is to be able to access the routing parameters collection and prevent the route from loading if a certain parameter is missing. I have tried using preventDefault in $routeChangeStart, b ...

Repeating Elements with Angular and Utilizing a Touch Keyboard

Currently, I am developing a table with various fields and the ability to add new rows. The goal is to display all the inputted data at the end. This application is specifically designed for touch screen monitors, so I have created a custom keyboard for in ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

Is it possible for you to simulate the shift key being pressed prior to the event execution?

Is there a way to allow the user to scroll left and right horizontally without having to hold the shift key down? I want to achieve this effect by setting the "shiftKey" variable to true even when it is not physically pressed. Any suggestions on how to ...

AngularJS 1.7.x's ngRoute tabs navigation post authentication

In my current project, I am using ngRoute to route users to the login page and upon successful login, they should land on the dashboard page. However, I am facing a problem with the dashboard page where I need to have two or more tabs that render HTML pag ...

Is there a way to prevent a user who is already logged in from accessing their account on a different browser or tab

My current stack consists of reactjs, nodejs, and redux for user authentication. I am utilizing aws cognito to handle the user authentication process. The main functionality of my app is uploading files from users to an s3 bucket. One of my goals is to p ...

What is the method for launching a new tab within an incognito window that is already open?

In the process of developing a Chrome extension, I am focusing on the functionality of creating a new tab from context menus within an incognito window. My current approach involves using the following script: chrome.windows.create({url: "https://google.c ...

Getting data in a ng-Dialog Modal with AngularJS is a breeze!

Hi there, I'm new to Angular JS and facing an issue with displaying data from my MySQL database in a table as well as in a modal for more detailed information: I've included the HTML file named _detail_modal.html at the bottom of the page. ...

Modifying arrays in ReactJS

Having trouble editing my array list, need some help. I can update a single input value successfully, but struggling with updating the entire array. Any suggestions on why the method isn't working and how to edit the array? When I try to store data ...

Scrolling automatically to a DIV is possible with jQuery, however, this feature is functional only on the initial

I'm currently working on a Quiz site and I've encountered a puzzling issue. Since the explanation only appears after an answer is selected - essentially a "hidden" element, I decided to wrap that explanation into a visible DIV. The code I'v ...

Arrange a set of items using AngularJS according to specific criteria

Hello, I'm new to Angular I've created an angular app and you can view it in this plunkr. Can someone guide me on how to sort the list displayed here using angular? I want the course with the flag to always stay on top, while sorting the rest o ...