What is the best way to animate a gltf model using threejs?

Is it possible to move a gltf model independently from the scene it's defined in three.js?

In my current code, I have an updated gltf model and attempted to move it using KeyboardState.js. The OrbitControl.js is being used for control.

You can find the KeyboardState.js code here:

This is the loading function that I am currently using:

function loadGLTF(x,y,z,mesh,url){
            var loader = new THREE.GLTFLoader();
                // model
                loader.load(
                        // resource URL
                        url,
                        // called when the resource is loaded
                        function ( gltf ) {

                            mesh = gltf.scene;
                            mesh.position.set(x,y,z);
                            scene.add(mesh);
                        },
                        // called while loading is progressing
                        function ( xhr ) {

                            console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

                        },
                        // called when loading has errors
                        function ( error ) {
                            console.log(error);
                            console.log( 'An error happened' );

                        }
                    );

        }

Here is the update function that handles keyboard input:

function update()
        {
            keyboard.update();

            var moveDistance = 50 * clock.getDelta(); 

            if ( keyboard.down("W") ) 
                mesh.translateY( moveDistance );

            if ( keyboard.down("S") ) 
                mesh.translateY(   -moveDistance );

            if ( keyboard.down("A") ){
                console.log("entered in A");
                mesh.translateX( -moveDistance );
            }

            if ( keyboard.down("D") ){
                console.log("entered in D");
                mesh.translateX(  moveDistance );
            }


            controls.update();
            stats.update();
        }

However, the issue arises where the object moves with the entire scene, rather than independently. It seems that this behavior does not occur when moving a simple sphere. Could it be due to the gltf file being inherently dependent on the scene structure compared to a standard THREE.SphereGeometry?

Answer №1

It appears that the KeyboardState is not being utilized correctly. The proper approach is to use the pressed() method to check if a specific key is pressed. In the following demonstration, you can observe that only the glTF model undergoes translation while the axes helper remains fixed at the center of the scene.

https://jsfiddle.net/kd41ejua/1/

Answer №2

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Demo</title>
  </head>
  <body>
    <script src="https://rawcdn.githack.com/mrdoob/three.js/d9f87fb1a2c5db1ea0e2feda9bd42b39b5bedc41/build/three.min.js
"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34405c46515174041a0c011a04">[email protected]</a>/examples/js/controls/OrbitControls.js"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79657f68684d3d23353a233c">[email protected]</a>/examples/js/loaders/GLTFLoader.js"></script>

    <script>
      var scene, camera, renderer;

      function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera(
          75,
          window.innerWidth / window.innerHeight,
          0.1,
          1000
        );

        scene.background = new THREE.Color(0xefefef);
        camera.position.set(5, 5, 5);

        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);
   
        var avtar;
        var loader = new THREE.GLTFLoader();
        loader.load(
          "https://rawcdn.githack.com/siouxcitizen/3DModel/a1c2e47550ca20de421f6d779229f66efab07830/yuusha.gltf",
          function (gltf) {
            avtar = gltf.scene;
            scene.add(avtar);
          }
        );

        controls = new THREE.OrbitControls(camera, renderer.domElement);

        document.onkeydown = function (e) {
          switch (e.keyCode) {
            case 37:
              avtar.scale.z += 0.1;
              break;
            case 39:
              avtar.scale.z -= 0.1;
              break;
          }
        };
        
        function animate() {
          requestAnimationFrame(animate);
          renderer.render(scene, camera);
        }

        animate();
      }

      init();
    </script>
  </body>
</html>

Give this code snippet a try!

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

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

Assign a class to an element depending on the date

I need to customize a span element in my HTML code like this. html <span class="tribe-event-date-start">September 5 @ 7:00 pm</span> My objective is to identify that specific element based on its date and then apply a class to its parent co ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

Managing State in React using Maps

As someone who is new to coding, I am currently facing an issue and seeking help to resolve it. I am using axios to retrieve a JSON file and store it in a state utilizing Redux for form population. I am then utilizing .map() to break down the array and dis ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Identify the distinct item by its name within the array

I need assistance in filtering out unique place names from the list Array's places Array. Below is an example of the array data=> "list":[ { "id":1, "uID": 1 "places":[ { ...

In JavaScript, use regular expressions to replace every instance of a link with its corresponding href object (map link -> a href=link)

I am looking to replace the following text: "wjjghwkjghwkjgh https://www.google.com jhgkwjhgkwhgk https://youtube.com" with: "wjjghwkjghwkjgh <a href='https://www.google.com'>https://www.google.com</a> jhgkwjhgkwhgk <a href=&a ...

In three.js, it appears that shadows are not being cast by imported 3D objects

Hey there, I've been diving into three.js recently and managed to successfully import a 3D model from Cinema 4D using the three.OBJMTLLoader. However, I'm having trouble getting the imported object to cast a shadow. I've tried setting object ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

JavaScript and the visibility of elements on a webpage

While working on the requirements for my project, I came across a specific task of hiding and unhiding a Div on the client side. The project is built using .net technology, and the visibility of the div is controlled on the client side through JavaScript. ...

What is preventing the control from transitioning to the script method known as "checkExistence()"?

I am currently working on a file upload program where I am utilizing an ajax call to verify if any file exists with the same name. Here is the snippet of code: JSP page <%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%&g ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

When using THREE.ParametricGeometry(func, slices, stacks), the function is executed multiple times

three.js:version:0.121 when I execute this piece of code, new THREE.ParametricGeometry( func, 200, 10) var func(u, v, point){ console.log(u,v) } output: 0 0 0.00001 0 0 0.00001 0.005 0 0.0049900000000000005 0 0.005 0.00001 0.01 0 0.00999 0 0.01 0.00001 0 ...

Is it possible to create a horizontal navigation bar with buttons that scrolls when media queries are activated? I am looking for a solution using HTML,CSS, JavaScript, and Bootstrap

Struggling to create a horizontally scrollable navigation with buttons for media queries in Bootstrap 5.2, using SCSS for styling. This project is starting to feel overwhelming as we try to replicate the EA site. We're aiming to mimic the behavior of ...

Conceal the excess content by placing it behind a series of stacked div

Within my layout, there is a fixed div called #navigation that houses buttons. Alongside this, there is scrollable content in the form of .card elements. The #navigation div currently displays with a green background for demonstration purposes, as shown b ...

AngularJS throws an error of TypeError when attempting to assign a value to a property that is undefined

I am trying to combine data.id with company.action.actions but I keep getting an error: TypeError: Cannot set property '10' of undefined This is my current code: company.action={}; company.getOptions=function(){ // company.action={ ...

Import the controller, factory, service, and directive files using Browserify

As I set up my AngularJS application in gulp-browserify, I aim for a clean and organized base structure to accommodate its anticipated size. In the main entry javascript file for browserify, I establish the main angular module and configure routes with ui ...

What could be the reason behind the infinite digestion loop triggered by my custom filter?

I devised a personalized filter that segregates an array of key-value pairs into an object based on grouping values by the first letter of a specific property. For instance Input: [{foo: 'bar'}, {faz: 'baz'}, {boo: 'foo'}] O ...

Showing a progress bar within a gulp pipeline

Can the progress bar be shown in gulp when transferring specific files? gulp.task('release:step-2', function() { return gulp.src(config.copy_src, { dot: true }) .pipe(gulp.dest(config.path.dest.app)); }); ...