How can we create dynamic animations with a counter in A-Frame?

I am looking for a more efficient method to sequentially execute animations one after the other, with each animation playing "X" number of times.

Due to the randomness of animations being selected from arrays, I cannot consolidate them into a single long GTLF/GLB animation.

The challenge I'm facing is how to repeat this code once it has completed its cycle.

Below is my current strategy:

// Counter (to determine when to play multiple animations sequentially)
var counter = 0;

// Number that counter needs to reach. Between 1 and 3 loops
function randomIntFromInterval(min, max) { 
   return Math.floor(Math.random() * (max - min + 1) + min);
};

var countertrigger = randomIntFromInterval(1,3);

// Default animation for Character
character.setAttribute("animation-mixer", {clip: "animationA"});

character.addEventListener('animation-loop', function () {
  if (character.getAttribute = character.getAttribute("animation-mixer", {clip: "animationA"})){
    counter++;

    if (counter === countertrigger){
      character.setAttribute("animation-mixer", {clip: "animationB"});

      character.addEventListener('animation-finished',function() {
        if (character.getAttribute("animation-mixer").clip === "animationB"){
          character.setAttribute("animation-mixer", {clip: "animationC"});

          character.addEventListener('animation-finished',function() {
            if (character.getAttribute("animation-mixer").clip === "animationC"){
              character.setAttribute("animation-mixer", {clip: "animationA"});

            // Resets idle counter
            counter = 0;

            // Resets/randomises the number of loops before next set of animations execute  
            countertrigger = randomIntFromInterval(1,3);
            };
          });
        };
      }); 
    };
  };
});

Answer №1

Whenever the animation-loop event is triggered and counter === countertrigger, a new event listener for animation-finished is generated, leading to a chain of callbacks.

There are various methods to handle this situation, here's one approach:

  • Store some variables (current counter, current animation)
  • Manage all logic within a single loop callback - deciding what should be in the next loop by checking the variable values.

Here's an example:


// initialize idle cycle counter
var counter = 0;

// Value counter must reach. Between 1 & 3 loops
function randomIntFromInterval(min, max) { 
  return Math.floor(Math.random() * (max - min + 1) + min);
};
var countertrigger = randomIntFromInterval(1,3);

// animation helper variables
var animations = ["animationA", "animationB", "animationC"]
var clipId = 0;

// start the animation
character.setAttribute("animation-mixer", {clip: animations[clipId});

// on each animation loop...
character.addEventListener('animation-loop', function () {
  // check if idle or needs to be idle longer
  if (clipId === 0 && counter < countertrigger) {
     counter++;
     return;
  }
  
  // check if this was the last animation
  if (clipId === (animations.length - 1)) {
     // Reset variables
     clipId = 0;
     counter = 1; // the animation will play once in this callback
     countertrigger = randomIntFromInterval(1,3);
  } else {
     clipId++
  }
  // play the next animation
  character.setAttribute("animation-mixer", {clip: animations[clipId]});
}

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

Exploring the possibility of utilizing the talks.js library to develop a chat feature within a React application

I'm currently working on integrating the talks.js library to set up a chat feature in my React project. I've followed all the instructions provided at , but unfortunately, it's not functioning as expected. I'm not quite sure what I migh ...

Utilizing VueJs @error handler for managing broken image links

I am encountering a strange issue with the VueJS @error handler. My goal is to hide images with broken links and display a placeholder instead. However, when I have two images with broken links, only the first image displays the placeholder while the other ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

After the ajax call has finished loading the page, I would like to toggle a particular div

When I trigger a click event on an element, it calls a function with Ajax calls. How can I toggle a div (which will be loaded after the Ajax call) once the page is loaded? function triggerFunction(){ $("#trigger_div").trigger("click"); $("#to ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

The execution of async.each does not complete successfully

I'm facing an issue with a simple function that retrieves the word count from a URL. The script runs smoothly with a low number of URLs, limiting the async to 4 at a time. I keep an eye on my RAM and CPU usage, but they never come close to maxing out. ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

Unable to retrieve the position of the loaded json models

Below is a sample json file representing a basic rectangular box. { "metadata" : { "formatVersion" : 3.1, "sourceFile" : "BOX.obj", "generatedBy" : "OBJConverter", "vertices" : 8, "faces" ...

React Module cannot be found: Error: Unable to locate - import paths

New to coding and currently working on a website using React. Encountering three errors persistently: ERROR in ./src/Components/Pages1/Home.js 6:0-50 Module not found: Error: Can't resolve './Components/Cards/Cards1.js' in 'C:\Use ...

What is the best way to display the nested information from products.productId?

How do I display the title and img of each product under the product.productId and show it in a table? I attempted to store the recent transaction in another state and map it, but it only displayed the most recent one. How can I save the projected informa ...

Tips for incorporating additional items into an established useState array utilizing map() or foreach()?

I'm working on developing a social media platform similar to Twitter, and I'm facing challenges with the news feed functionality. Essentially, the news feed is supposed to fetch tweets from my firebase database for each user followed by the curre ...

Don't forget to preserve the hover state of divs even after refreshing

I recently added a navigation bar that expands in width upon hovering over it. For an illustration, check out this example: http://jsfiddle.net/Gsj27/822/ However, I encountered an issue when clicking on a button within the hover effect area. After load ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

Node.js encounters issues when attempting to rename a folder

I am facing an issue while attempting to rename a folder within a WordPress theme after performing search-replace operations using a node script. The renaming process for the folder seems to be unsuccessful. My objective is to change this public_html/wp- ...

Checkbox: Activate button upon checkbox being selected

On my webpage, I have a modal window with 2 checkboxes. I want to enable the send button and change the background color (gray if disabled, red if enabled) when both checkboxes are selected. How can I achieve this effectively? HTML: <form action="" me ...

Is it possible to use the identical change function on numerous div elements?

How can functions be bound to multiple div elements effectively? $('#trigger1').change(function(){ // implement the code }); $('#trigger3').change(function(){ // execute the same code }); ...

Are there any available npm modules for accurately tallying the total word count within a document saved in the .doc or .doc

I Need to tally the number of words in doc/docx files stored on a server using express.js. Can anyone recommend a good package for this task? ...