Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players will take care of phrogs instead of frogs, and I want the phrogs to randomly croak as an idle animation. As the game progresses, I plan to incorporate additional random animations for movements, eating, etc. However, at the moment, I am solely focused on implementing the croaking animation.

Below is the code snippet used to load and animate the model:

const basePhrog = new GLTFLoader()
var obj
basePhrog.load('assets/models/Phrogs/base phrog/phrog.gltf', function (gltf) {
  mixer = new THREE.AnimationMixer(gltf.scene)
  obj = gltf.scene
  var action = mixer.clipAction(gltf.animations[0])
  scene.add(gltf.scene)
  action.play()
})

This is the structure of my animate loop:

function animate () {
  requestAnimationFrame(animate)
  var delta = clock.getDelta()
  if (mixer) mixer.update(delta)
  renderer.render(scene, camera)
}
animate()

I would greatly appreciate any suggestions or guidance on achieving the random animation intervals. Thank you in advance for your assistance!

Answer №1

The glTF file includes an animation (or THREE.AnimationClip in the three.js framework), and the playback of this animation is controlled by an instance of THREE.AnimationAction. In the provided code snippet, the animation starts playing immediately and loops indefinitely, but this is not the only way to use AnimationAction.

Alternatively, you can choose to play the animation at random intervals:

var action = mixer.clipAction( animation );
action.loop = THREE.LoopOnce;

// Play animation randomly every 1-10s.
setInterval(() => {
  action
    .reset()
    .play();
}, Math.random() * 9000 + 1000);

You can continue updating the AnimationMixer as usual, regardless of whether the animation is currently playing or not.

If you plan to play multiple animations on the same object later on, you may find some transitional APIs useful for switching between two animations. Refer to the animation / skinning / morph example for more information.

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

Navigate to a precise point in a video using react hooks in videojs

I am currently working on adding a feature that allows users to skip forward or backward by 15 seconds in a video. However, I am encountering difficulties when it comes to updating and setting the current time accordingly. const videoNode = useRef(null); ...

Enhancing the mobile menu with a feature that allows users to easily close the

I am currently designing a mobile menu for a website that I created using Wordpress with the Divi Theme. When the user clicks on a "hamburger icon", it triggers a fullscreen menu to open: mobile menu If you tap on "Termine", it will reveal a submenu: mo ...

What sets apart jQuery.ajax's dataType="json" from using JSON.parse() for parsing JSON data?

What is the difference between using dataType='json' and parsing response with JSON.parse(response) in jQuery Ajax? $.ajax({ url: path, type: 'POST', dataType: 'json', data: { block ...

employing async/await in the function of a backend API

I'm facing an issue with the following code snippet: service.js module.exports = { getUser }; async function getUser({ data }) { return new Promise((resolve, reject) => { const id = data["id"]; const doc = await db.colle ...

Updating the functionality of one-page scrolling - changing to overlap instead of sliding upwards

Hello, I am currently utilizing a JavaScript library to create a website with full page scrolling. If you want to know about the library, check out this link: For those interested, here is an example of my work on jsfiddle: http://jsfiddle.net/aLjLjxux/ ...

The model in the Schema has not been registered, unlike other models from the same source that have been successfully registered

When populating a node express route with information from Schemas, I encountered an error that puzzles me. Even though I am referencing three different fields in the same Schema, I am only facing this error for one of those fields. The specific error mes ...

Choosing values from a variety of select option boxes using jQuery

I'm experiencing an issue with selecting values in a multiple select option box. Despite my efforts, I haven't been able to get all the desired items selected at once. Currently, when I run the code below, only the first option is being selected ...

Stop the scrolling behavior from passing from one element to the window

I am facing an issue with a modal box window that contains an iframe. Inside the iframe, there is a scrollable div element. Whenever I try to scroll the inner div of the iframe and it reaches either the top or bottom limit, the browser window itself start ...

Tips for Editing and Modifying Name and Area in a Database

I'm currently working with React to develop a full CRUD application, but I'm facing challenges in updating the names and areas of rooms within houses. Any suggestions or insights on how to achieve this would be greatly appreciated. Apologies for ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

Having trouble generating an image with JavaScript

I am currently working on incorporating an image onto a webpage using JavaScript. Surprisingly, even the alert('This function works!') is not displaying anything! What could be causing this issue? Please assist! <!DOCTYPE html> <html> ...

When using Angular, it is important to remember that calling `this.useraccount.next(user)` may result in an error stating that an argument of type 'HttpResponse<any>' cannot be used with a 'Useraccount' balance

When attempting to use this.useraccountsubject(user) to insert information upon login, I encountered an error: ErrorType: this.useraccount.next(user) then Error An argument of type 'HttpResponse' is not allowed against a balance of 'Userac ...

Learn how to implement a vertical bar chart in Highcharts by using it as a component and passing it as props

I recently imported a Bar Chart component from Highcharts, but it is being displayed horizontally. I would like to convert it into a vertical chart instead. Can someone please assist me in achieving this by passing the necessary props? <template v-slot ...

Rotate a sphere in three.js in order to align the mapped image of the globe with the GeoJSON data that is displayed in the same three

I have successfully implemented a globe in three.js with an image mapped onto the sphere. Furthermore, I am utilizing the ThreeGeoJSON library to visualize geojson data on top of the globe. However, the geographies from the geojson data do not align corr ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...

Executing several asynchronous functions in Angular 2

I am currently developing a mobile app and focusing on authentication. In order to display data to the user on my home page, I need to connect to various endpoints on an API that I have created. Although all endpoints return the correct data when tested i ...

React state change is causing a functional component to not re-render

When attempting to map out a nested array from the data retrieved by an http request in a functional component, you may encounter a frustrating error: "TypeError: Cannot read property 'map' of undefined". Even though the state is updated correctl ...

Responsive menu is failing to respond to the click event

I'm facing an issue with my responsive menu on mobile phones. It should display two buttons - one for the navigation bar and the other to toggle the side bar by removing the classes hidden-xs and hidden-sm. However, I am having trouble getting the btn ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...