Surprising gltf file animations in react-three caught me off guard

Using the react-three package, I attempted to import gltf files into my react app. To my surprise, the 3d model did not autoplay after the rendering. Initially, I thought it was an animation glitch, but the peculiar part was that when scrolling up or down, the model would move sporadically, just a frame or two. Furthermore, upon clicking the model, it would animate normally...until it didn't.

I'm currently puzzled by this strange behavior. Can anyone offer assistance? Thank you!

DEMO: (The robot model and the floating balls below are experiencing the same issue)

Code snippet for the robot model:

import React, { Suspense, useEffect, useState } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { OrbitControls, Preload, useGLTF } from "@react-three/drei";
import CanvasLoader from "../Loader";
import * as THREE from "three";

const Robot = ({ isMobile }) => {
  const { scene, animations } = useGLTF("./robot/scene.gltf");
  let mixer = new THREE.AnimationMixer(scene);
  animations.forEach((clip) => {
    const action = mixer.clipAction(clip);
    action.play();
  });
  useFrame((state, delta) => {
    mixer.update(delta);
  });

  return (
    <mesh>
      <hemisphereLight intensity={0.15} groundColor="black" />
      <spotLight
        position={[-20, 50, 10]}
        angle={0.12}
        penumbra={1}
        intensity={1}
        castShadow
        shadow-mapSize={1024}
      />
      <pointLight intensity={1} />
      <primitive
        object={scene}
        dispose={null}
        scale={isMobile ? 2 : 1.6}
        position={isMobile ? [-10, -6, -2] : [-2, -4, 0]}
        rotation={isMobile ? [0, 1.5, 0] : [0, 1.3, 0]}
      />
    </mesh>
  );
};

const RobotCanvas = () => {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    // Add a listener for changes to the screen size
    const mediaQuery = window.matchMedia("(max-width: 450px)");

    // Set the initial value of the `isMobile` state variable
    setIsMobile(mediaQuery.matches);

    // Define a callback function to handle changes to the media query
    const handleMediaQueryChange = (event) => {
      setIsMobile(event.matches);
    };

    // Add the callback function as a listener for changes to the media query
    mediaQuery.addEventListener("change", handleMediaQueryChange);

    // Remove the listener when the component is unmounted
    return () => {
      mediaQuery.removeEventListener("change", handleMediaQueryChange);
    };
  }, []);

  return (
    <Canvas
      frameloop="demand"
      shadows
      dpr={[1, 2]}
      camera={{ position: [20, 3, 5], fov: 25 }}
      gl={{ preserveDrawingBuffer: true }}
    >
      <Suspense fallback={<CanvasLoader />}>
        <OrbitControls
          enableZoom={false}
          maxPolarAngle={Math.PI / 2}
          minPolarAngle={Math.PI / 2}
        />
        <Robot isMobile={isMobile} />
      </Suspense>

      <Preload all />
    </Canvas>
  );
};

export default RobotCanvas;

Answer №1

After a suggestion from @Don McCurdy, it was discovered that the issue lied within the line frameloop="demand. Once this line was removed, the model functioned perfectly. This tip may prove to be beneficial for other developers encountering a similar problem.

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

ESLint error caught off guard by function expression in customized MUI Snackbar Component with Alert

Struggling to create a personalized MUI Snackbar using the MUI Alert example from the official Documentation, but facing ESlint errors: error Unexpected function expression prefer-arrow-callback error Prop spreading is forbidden react/jsx-props-no-s ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

Save the function as a local variable and preserve the reference to the current object

In the prototype of my Car object, I have a function that looks like this: Car.prototype.drive = function() { this.currentSpeed = this.speed; } I find myself needing to call this drive function frequently within another function of the Car prototype. ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

Tips for setting a unique JWT secret in next-auth for production to prevent potential issues

Is there a way to properly set a JWT secret in NextAuth.js v4 to prevent errors in production? I have followed the guidelines outlined in the documentation, but I am still encountering this warning message without any further explanation: [next-auth][warn] ...

Issues have been encountered with jQuery on function when it comes to dynamically inserted elements

I have been trying to utilize the .on method for dynamically created elements, but it doesn't seem to be working as expected. I am using a selector though :) $(".metadata").on("click", "i.icon-remove", function () { console.log("what"); $(thi ...

Input the date manually using the keyboard

I am currently utilizing the rc calendar package available at https://www.npmjs.com/package/rc-calendar When attempting to change the year from 2019 to 2018 by removing the "9," it works as expected. However, when trying to delete the entire date of 1/15/2 ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

Remove HTML element and launch in a separate browser tab while preserving styles

I am currently working on developing a single-page application with Polymer3 (Javascript ES6 with imports). One of the key functionalities of my application involves moving widgets to new browser windows, allowing users to spread them across multiple scree ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Triggering Various Button Click Actions with Jquery Event Handlers

Is it possible to attach several Button Click events to the same function like the example below? $(document).on("click", "#btn1 #btn2 #btn3", callbackFunction); ...

What is the best way to supply arguments to a generic handler function?

How can I send parameters to a generic handler in Asp.net using JavaScript/jQuery? I am working on a jQuery plugin called ajaxfileupload that utilizes a generic Handler. I need to pass certain arguments from the page using jQuery or JavaScript, such as Dy ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

What is the procedure for canceling a readline interface inquiry?

TL;DR I encountered an issue with the native Node.js Readline module. Once a question is asked using rl.question(query[, options], callback), it seems there is no straightforward way to cancel the question if it's pending an answer. Is there a clean ...

Using BootstrapValidator for conditional validation

While utilizing the BootstrapValidator plugin for form validation, I encountered a specific issue. In my form, I have a "Phone" field and a "Mobile" field. If the user leaves both fields blank, I want to display a custom message prompting them to enter at ...

Ensure that every HTML link consistently triggers the Complete Action With prompt on Android devices

After extensive searching, I have yet to find a solution to my issue. I have been developing a web application that allows users to play video files, primarily in the mp4 format. Depending on the mobile browser being used, when clicking the link, the vide ...

How does the Rx subscribe function maintain its context without the need to explicitly pass it along

Currently, I am utilizing Rx with Angular2 and making use of the Subscribe method. What intrigues me is that the callbacks of the method are able to retain the context of the component (or class) that initiated it without needing any explicit reference pas ...

Assign the private members of the class to the arguments of the constructor

class Bar { #one #two #three #four #five #six #seven #eight #nine #ten #eleven #twelve #thirteen #fourteen #fifteen #sixteen constructor( one, two, three, four, five, six, seven, eight, ...

Runs tasks asynchronously in a sequential manner

I am attempting to run two functions asynchronously in series using node.JS, but I am struggling with the implementation. Currently, my code looks like this: Function 1: function search(client_id, callback) { clientRedis.keys('director:*', ...