Animate the Collade object's position gradually in ThreeJS

In my ThreeJS project, I am working with the elf example from ThreeJS

Instead of simply rotating the object as shown in the example, I want to move it in both the x and y directions. To achieve this, I plan on updating the elf.position.x and elf.position.y values within the init() function.

The issue I am currently encountering is related to creating multiple instances of the elf object using a method within a class. Additionally, I have a function intended to move the object over time. However, I am unable to access the e variable within the move function. When attempting to change it to this.e and updating e = collada.scene; to this.e = collada.scene;, I receive an error stating:

Uncaught TypeError: Cannot set property 'e' of undefined

Here is the code snippet:

 class DrawElf {
    constructor(scene) {
        var e;
        this.loadingManager = {};
        this.loader = {};
        this.scene = scene;

        // loading manager
        this.loadingManager = new THREE.LoadingManager(function () {
            scene.add(e);
        });

        // collada
        this.loader = new THREE.ColladaLoader(this.loadingManager);
        this.loader.load('./models/collada/elf/elf.dae', function (collada) {
            e = collada.scene;
            e.scale.set(30, 30, 30);
            e.position.set(100, 10, 100);
            e.name = "elf.dae" + 0 + 0;

            e.traverse(function (child) {
                if (child instanceof THREE.Mesh) {
                    child.name = e.name;
                    ToIntersect.push(child);
                }
            });
        });
    }

    move(time) {
        // logic for moving the object goes here
    }
}

I would appreciate any assistance with this problem.

Answer №1

I have made some modifications to your code example to demonstrate how to access the elf model within the move() function and highlighted these changes in the comments below.

class DrawElf {
    constructor(scene) {

        // Update 1: Stored the `e` variable on `this` for accessibility
        // within member functions like `move`
        this.e = null;
        this.loadingManager = {};
        this.loader = {};
        this.scene = scene;

        // Update 2: Utilized arrow functions instead to maintain the scope of
        // the constructor in the callback, ensuring that `this` still refers to
        // the new instance of `DrawElf`
        // collada
        this.loader = new THREE.ColladaLoader();
        this.loader.load('./models/collada/elf/elf.dae', (collada) => {
            this.e = collada.scene;
            this.e.scale.set(30, 30, 30);
            this.e.position.set(100, 10, 100);
            this.e.name = "elf.dae" + 0 + 0;

            this.e.traverse(function (child) {
                if (child instanceof THREE.Mesh) {
                    child.name = this.e.name;
                    ToIntersect.push(child);
                }
            });

            // Update 3: Removed the loading manager as it is unnecessary for adding
            // the elf to the scene, and accomplished the task here instead
            scene.add(this.e);
        });
    }

    move(time) {
        // Update 4: Verified if the scene has been loaded before attempting to
        // manipulate the model
        if (this.e) {
            // perform model movements here
        }
    }
}

The major revision includes switching to arrow functions from traditional Javascript functions so that this maintains reference to the object being constructed. More information about scoping variations can be found in this StackOverflow explanation.

I hope this clarifies things! Feel free to ask if you need further clarification.

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

Attempting to iterate over a JSON object and display its contents using HTML

I have been attempting to iterate through this JSON data and display it in an accordion format similar to the one shown here: but unfortunately, my implementation is not functioning correctly. Here is what I currently have: HTML: <div class="a ...

What could be the reason a normalMap fails to render accurately while utilizing THREE.SubdivisionModifier?

When attempting to render a 'soft' cube with a normal map, I encountered an issue. Despite not receiving any errors or warnings while running the code, adding the normal map parameter resulted in a black object when refreshing the browser. Removi ...

Explore nested arrays and retrieve objects that have corresponding categories

Working with react+ nextJS and fetching static objects, specifically "posts". The aim is to develop a "related posts" feature for each post that retrieves three posts containing at least one of the categories. Below is an excerpt simplified for clarity: co ...

When utilizing the map function with an array containing 168 objects in the state of a React application, a freeze of around 1

I encountered an issue when trying to update a property in a state array of objects after executing an axios.put request. Here is my code: States - useEffect //... const [volunteers, setVolunteers] = useState([]); //... useEffect(() => { async fu ...

Guide on triggering an open modal when clicking a link using jQuery

Creating a modal popup has always been my goal. After designing the CSS to style it, I found myself stuck as I lack knowledge in JQuery or JavaScript to code the functionality that animates and opens the modal upon clicking a button or link. Despite search ...

Targeting Multiple Ids with ModalPopUp Extender

Greetings everyone! Let's get started! So, I have a couple of buttons on my page and I want to use one modal popup for both save clicks. Here is the code for the buttons: <asp:Button ID="btnSave1" runat="server" OnClick="btnSave1_Click" Text="Sa ...

Storing Mongoose records with null sub-document collections leads to a duplicate key constraint violation

I have encountered an issue with two mongoose schemas that I am working with. var productSchema = new Schema({ name: { type: String, required: true, unique: true }, ... }); ... var categorySchema = new Schema({ ... products: [ProductSchema ...

Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider ma ...

Executing numerous HTTP requests in a single Node.js HTTP request

I am attempting to make a single URL call that will fetch multiple URLs and store their JSON responses in an array, which will then be sent as the response to the end user. Here is what my code looks like: var express = require('express'); var ...

Are iFrames being utilized for third-party applications?

I am looking to create a web application that can be extended by other developers with their own applications. Would using iFrames, similar to how Facebook does it, be the best approach? Is this considered a good practice in web development? Are there a ...

Step-by-step guide for adding an icon to the corner of a Material UI button

Is there a way to position an icon in the corner of a Material UI button in React? Currently, I have the icon next to the title but I would like to move it to the lower right corner of the button. Any suggestions on how to achieve this? Thank you! export ...

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

Troubleshooting a manual installation of the mysql2 package - encountering an

I've encountered an issue while trying to initialize Sequelize in my application. When using docker-compose to build and run the app, I am prompted to manually download the mysql2 package. Despite my attempts to download it using various methods like ...

AJAX not showing validation error message

For the past two days, I've been grappling with an issue and can't seem to pinpoint where it's coming from. After leaving the textbox, the Ajax call functions correctly and returns results as either true or false, triggering the success fun ...

Customizing CSS according to specific URLs

I have two different domains - one ending with .nl and the other ending with .be. For instance, domain.nl and domain.be. Both domains share a similar overall style, but I want certain elements to have distinct styling depending on whether it is the .nl o ...

leveraging npm packages in Vue single page applications

I recently developed a Vue.js application using vue-loader and now I am trying to integrate an npm package that I have installed. Here is the code snippet: var x = require('package-name') Vue.use(x) However, I encountered the following ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

Drawing a line in THREE JS where the endpoint is a vector not related to the object or its parent

In my scene, I have a hierarchy of objects where one is the parent and the other is the child. My goal is to determine a Vector3 relative to the deepest child object that points towards a specific vector in the scene (look_point). var grandParent = new T ...

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

Error message: "Expression value changed after checking in Ionic 2 range slider causing"

Currently, I am in the process of developing an audio player using the javascript Audio() object within Ionic 2. However, there seems to be an issue with the Ionic 2 range slider attached to the audio player. The progress on the slider does not update auto ...