Three.js: Wanting to create objects and add motion along a curved path

In an attempt to create a unique effect, I am exploring the idea of spawning a series of objects on a setInterval and assigning each object a customized animation on a path using requestAnimationFrame. I have successfully added one object and animated it along a path with the following code:

var psGeometry = new THREE.PlaneGeometry(3,2,10,1);
var psPlane = new THREE.Mesh(psGeometry, new THREE.MeshBasicMaterial({color:0x0000ff}));
scene.add(psPlane);

function animatePaper(obj = psPlane, offset= 0.007)
{
    if(counter <=( 1-obj.geometry.vertices.length/2 *offset))
    {
        for (var i=0; i < obj.geometry.vertices.length/2; i++)
        {
            obj.geometry.vertices[i].y = curvePath.getPoint(counter + i * offset).y;
            obj.geometry.vertices[i].z = -0.5;
            obj.geometry.vertices[i + obj.geometry.vertices.length/2].y = curvePath.getPoint(counter + i * offset).y;
            obj.geometry.vertices[i + obj.geometry.vertices.length/2].z = -2.5;

            obj.geometry.vertices[i].x = curvePath.getPoint(counter + i * offset).x;
            obj.geometry.vertices[i + obj.geometry.vertices.length/2].x = curvePath.getPoint(counter + i * offset).x;

        }
        obj.geometry.verticesNeedUpdate = true;

        counter += 0.005;
    }
    else{
        console.log("Removing...");
        scene.remove(obj);
    }
}
function animate() {
    requestAnimationFrame(animate);
    animatePaper(psPlane, 0.007);
    render();
}

View the example here: jsfiddle.net.

While this animates the object along the curvePath, I thought it would be possible to spawn these objects at intervals and apply the same code. Unfortunately, this was not the case.

My attempts: I tried creating a function to spawn objects and apply the code:

setInterval(drawSheets, 1000); 
function drawSheets()
{
    var psGeometry = new THREE.PlaneGeometry(3,2,10,1);
    var psPlane = new THREE.Mesh(psGeometry, new THREE.MeshBasicMaterial({color:0x0000ff}));
    scene.add(psPlane);
    setInterval(function(){animatePaper(psPlane, 0.007);}, 30);
}

I also attempted the method suggested in this answer:

setInterval(objArray.forEach(function(obj){setInterval(function(){animatePaper(obj);},300);}), 3000);

Expected outcome: To spawn multiple objects at intervals and independently animate each one along a curve.

I am looking for assistance on this matter. Thank you!

Version: Three.js r82

** EDIT: ** After conducting another test (jsfiddle), I discovered that using setInterval on a function results in shared variables, speeding up the animation. I am seeking advice on how to localize these variables to each object.

Answer №1

To enhance your animation, consider organizing your Path and Plane objects into arrays, one for Paths and another for Planes. Include their unique offsets or values, then iterate through them in an update function within your animation loop using the animatePaper function.

Here's a simple pseudo code example:

var planesAndMeshesArray = [ 
    { path1 : (your plane), plane1 : (your mesh), offset : (offset value), extrudeSettings : (settings object) }, 
    { path2 : (your plane), plane2 : (your mesh), offset : (offset value), extrudeSettings : (settings object) }, 
    { path3 : (your plane), plane3 : (your mesh), offset : (offset value), extrudeSettings : (settings object) },
...]

- Generate random values for the above array within a suitable range for desired effects
- Iterate through the array to add each mesh and plane to the scene     

function update() {
    - Use a loop to update each object by utilizing the `animatePaper` function on the array. This array acts as references to the objects in your scene - any changes made in the array reflect in the scene. 
    - Remember to update your controls as well
}

function animate() {
    requestAnimationFrame(animate);
    update();
    render();
}

For a more advanced approach, you can implement object-oriented Javascript to create your curve-and-paper objects. Start with the array structure and gradually introduce complexity as necessary.

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

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

When attempting to call a class in Node.js with Express, the return value is coming back

I am relatively new to working with Node.js and the Express framework. I am attempting to pass a value to a JavaScript class in order to process a query and make a call to the database, expecting to receive a result array. Here is the code snippet I am cur ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Traditional method for comparing prevProps in componentDidUpdate

As I work on prototyping, I've noticed that when new props come in as an array of complex objects, prevProps.myProp===this.props.myProp always returns false. While using JSON.stringify for comparison seems to work, it doesn't feel very reliable. ...

How to Validate Prop Types in VueJS When Dealing With NULL and 'undefined' Values?

Despite what the official VueJS 2 documentation on prop validation says in a code example comment: // Basic type check (null and undefined values will pass any type validation) I encountered an error while testing this piece of code — could you explai ...

Deleting information from several stores in React Reflux using a single action function

In the AuthActions file, there is a straightforward function called _clear that assigns this.data to undefined. This function is only invoked when a user logs out. However, upon logging back in with a different user, remnants of data from the previous ac ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

Extract the JSESSIONID and generate a new Cookie using AngularJS

Currently, I am utilizing a Web RESTful API from my client within AngularJS. app.controller('LoginController', [ '$http', '$cookies', function($http, $cookies) { this.credentials = {}; this.http = $ ...

Identifying instances where the AJAX success function exceeds a 5-second duration and automatically redirecting

Greetings! I have created a script that allows for seamless page transitions using Ajax without reloading the page. While the script functions perfectly, I am seeking to implement a feature that redirects to the requested page if the Ajax request takes lo ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

jQuery droppable: Encounter of an unexpected TypeError: undefined lacks the characteristics of a function

I'm trying to implement drag and drop functionality on my website. However, I am encountering an error message in the console that says: Uncaught TypeError: undefined is not a function ... presentation-categories.js?version=1:23. The error occurs at ...

jQuery struggles to process large response

I am currently developing an application that sends requests to a URL and parses the table found in the HTML response using jQuery. While this method works well for smaller amounts of HTML code, it runs into issues with larger datasets. The problem arises ...

The SyntaxError message indicates that there was an unexpected non-whitespace character found after the JSON data when parsing it

I received an Error message: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data Here is the code snippet: <script> $(document).ready(function () { $('.edit1').on('change', function () { ...

Notification access is consistently denied

In my coding work, I rely on Notification.permission to determine if the browser supports notifications or not. Here's a snippet of how I handle Notification.permission in my script: // Verify browser notification support if (!("Notification" in windo ...

I am encountering an issue where the key is not located in the response array in PHP, causing my JavaScript chart to remain

Hey there! I'm currently working on a school project and could really use some assistance. The task at hand involves creating a web interface that can interact with an endpoint in order to: - Authenticate a registered user to retrieve an authenticati ...

Adjust the size of the canvas element based on changes to its parent's dimensions

I am working with an application that includes a div containing a canvas element to display an image. Additionally, there is a sidebar that can be hidden with the click of a button, causing all other elements to resize and adjust to the remaining space. W ...