Guide to managing .glb model animations in A-FRAME using Three.js

Can someone assist me with playing a glb animation in A-FRAME using Three.js? The animation works for a second and then stops. Here is my current code:

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<script>
AFRAME.registerComponent('move', {
  init: function () {
    setTimeout( () => {
      let position = this.el.getAttribute("position")
   console.log(this.el.components['gltf-model'].model )
            // Create an AnimationMixer, and get the list of AnimationClip instances
      const mixer = new THREE.AnimationMixer( this.el.components['gltf-model'].model);
      const clips = this.el.components['gltf-model'].model.animations[0];
      var clock = new THREE.Clock();
      // Play all animations

    mixer.clipAction( clips ).play();
   //In the animation block of your scene:
      var delta = 0.25 * clock.getDelta();
      mixer.update( delta );
    }, 2000)
  }
})
</script>

  <a-scene>
      <a-entity gltf-model="https://rawcdn.githack.com/BabylonJS/MeshesLibrary/55f475726670be2e7e4017b5f88c5762a90508c2/shark.glb" move position=".5 0.5 -5" scale="0.5 0.5 0.5"></a-entity>                                                        
  </a-scene>

Answer №1

Controlling animation within a-frame involves utilizing the predefined animation-mixer component provided by aframe extra's library.

<head>
  <script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/donmccurdy/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50313622313d357d3528242231231026667e617e61">[email protected]</a>/dist/aframe-extras.min.js"></script>
</head>
<body>
  <a-scene>
    <a-entity id="model"
      gltf-model="https://rawcdn.githack.com/BabylonJS/MeshesLibrary/55f475726670be2e7e4017b5f88c5762a90508c2/shark.glb"
      position=".5 0.5 -5" scale="0.5 0.5 0.5"></a-entity>
  </a-scene>
  <script>
    document.getElementById("model").setAttribute("animation-mixer", "clip:swimming");
    const timedelay = setTimeout(delayFunction, 2000);
    function delayFunction() {
      document.getElementById("model").setAttribute("animation-mixer", "clip:bite");
    }
  </script>
</body>

By specifying the desired animation in the clip attribute, you can dynamically play different animations based on your program logic. Consult this resource for further guidance. In the example code provided, the swimming animation is played first followed by the bite animation after a 2-second delay.

Answer №2

  1. Ensure the model is fully loaded by using the following code:

    this.el.addEventListener("model-loaded", evt => /* stuff */)}
    
  2. Update the animation in each frame render - utilize the tick function provided by aframe for this purpose.

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent('move', {
    init: function() {
      // ensure model is loaded
      this.el.addEventListener("model-loaded", evt => {
        const mixer = new THREE.AnimationMixer(this.el.components['gltf-model'].model);
        const clips = this.el.components['gltf-model'].model.animations[0];
        mixer.clipAction(clips).play();
        // "expose" the animation mixer
        this.mixer = mixer;
      })
    },
    // update on each frame render
    tick: function(t, dt) {
      if (!this.mixer) return; // check if mixer exists
      this.mixer.update(dt / 1000); // update with delta time
    }
  })
</script>

<a-scene>
  <a-entity gltf-model="https://rawcdn.githack.com/BabylonJS/MeshesLibrary/55f475726670be2e7e4017b5f88c5762a90508c2/shark.glb"
  move position=".5 0.5 -5" scale="0.5 0.5 0.5"></a-entity>
</a-scene>

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

Preserving Search and Filter Settings in jQuery Data Tables

I've been working with a datatable and I'm trying to figure out how to keep dropdown filters and search parameters saved when the page is reloaded, just like shown in the screenshot below. However, I also want these parameters to be cleared if th ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

Creating a JavaScript function to selectively blur elements while leaving one in focus

My goal is to blur all elements on a webpage except for the p#this tag using vanilla JavaScript. I am determined to learn the intricacies of JavaScript, so I'm not looking for solutions involving jQuery or CSS. I came across a potential solution on t ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

Developing desktop applications with Angular 2 using NWjs

Looking to create an Angular 2 Desktop App using NWjs. Where can I find the entry point? Could someone provide some examples of developing Angular 2 Desktop Apps with NW.js? ...

SB Admin 2 menu with multiple levels does not collapse as expected

I'm in the process of integrating the menu from the sb admin 2 template into my Ruby on Rails application: As I gradually added components to test functionality, I successfully implemented the top and side nav bars. However, I encountered an issue wi ...

Retrieve the value of an object from a string and make a comparison

var siteList = {}; var siteInfo = []; var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]'; var part = part_str.substring(1,part_str.length-1); eval('var partobj='+part ); console.log(par ...

Steps to execute a JSON file once another JSON has been successfully loaded

I'm facing a similar challenge to the one presented in this question. However, I need to load an additional JSON file after the when() method is executed. Essentially, I want to retrieve JSON data within the when() function and then use that informati ...

Turn off laptop camera to assess web application functionality in the absence of a camera on the device

In the process of creating an automated testing framework in Java and Selenium, I have encountered a scenario where I need to examine how a web application behaves when accessed by a user with a device lacking a camera. Is there a method to simulate this ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

The email protected function is failing to display components and is not generating any error logs

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05776064667128776a7071607728616a6845332b31">[email protected]</a> seems to be having trouble rendering components. I've been away from React for a bit and now I ...

Submit simple text via XMLHttpRequest to an Express server

I am currently facing an issue with making a post XMLHttpRequest to my Express server. Despite attempting to send a string, it seems that I am missing something crucial in my implementation. Client: const sendMessage = () => { const message = "This ...

Retrieving journal web addresses using the CORE API

I am currently working on pulling journal data from the CORE API in React, specifically focusing on obtaining the title and URL of each journal. My goal is to create clickable links that direct users to the specified URLs. { "identifiers": [ ...

``If you're looking to retrieve, modify, and display information in your Vue application with the help of

I'm facing an issue where I am trying to retrieve data using the axios get request and then updating it based on the response of another axios get request. However, I am unable to display the data from the second request. The following is a snippet o ...

Querying Parse Server for objectId information

Within my web app that utilizes the Parse Server Javascript SDK, I have implemented the following query. While the console log accurately displays the retrieved information, the objectId field appears as "undefined." var query = new Parse.Query("myClass") ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

Change the DER encoded ANS.1 format of an AWS KMS ECDSA_SHA_256 Signature to JWT base64url encoded R || S format using NodeJS/Javascript

I am currently working on generating a JWT Signature in NodeJS using the ES256 algorithm and AWS KMS Customer Managed Keys. However, I have encountered an issue where the signature created by AWS KMS with ECDSA_SHA_256 cryptographic Signing Algorithms is ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

Bidimensional Selenium matrix

Could someone please help me understand how to extract values from a bi-dimensional array using Selenium? I have a resources.js file with the array created, and need to access it in Selenium. Here is the structure of the array: The array consists of 4 col ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...