Error: Unspecified object found in Three.js file

I am facing an issue where I have declared a global variable to store an OBJ loaded through THREE.OBJLoader, but when trying to animate the position or rotation of the object, I receive an error stating that the variable is undefined.

Below is how I have set up the scene including the variable spaceCraft:

    <script>
    var container;

    var camera, scene, renderer;

    var mouseX = 0,
        mouseY = 0;

    var windowHalfX = window.innerWidth / 2;
    var windowHalfY = window.innerHeight / 2;

    var spaceCraft;

    init();
    animate();


    function init() {

        container = document.createElement('div');
        document.body.appendChild(container);

        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
        camera.position.z = 250;

        // Rest of the initialization code...

Here is how I load my model:

        // Model loading

        var loaderModello = new THREE.OBJLoader(manager);
        var OBJPath = 'spaceCraft3.obj';
        spaceCraft = loaderModello.load(OBJPath, function(object) {

            // Loading and setting up the object...

Lastly, here are the animate() and render() functions:

        //

    }

    function onWindowResize() {
    
        // Resizing logic...

    }


    // Rest of the resize, mouse move and animation logic...

</script>

If anyone could provide some guidance on what might be causing this issue or suggest any improvements in clarity, it would be greatly appreciated. Thank you!

Answer №1

When dealing with THREE.js, it's important to remember that you're working with JavaScript. You can't redeclare a global variable as the loader result, but you can add to an object instead.

An effective way to handle this in modern JavaScript (ES6+) is to pass the variable through a function:

(function(spacecraft, object) {

THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );

var mtlLoader = new THREE.MTLLoader();

mtlLoader.load( 'js/m.mtl', (function( weapon, object ) {

  return function(materials) {        
        materials.preload();
    var objLoader = new THREE.OBJLoader();
            objLoader.setMaterials( materials );
            objLoader.load( 'js/m.obj', (function ( weapon, object ) {
            return function(wp) {                

                // Perform operations on the object
                wp.position.set(weaponslot.x,weaponslot.y,weaponslot.z);
                wp.rotateZ(Math.PI);
                object.add( wp );

                }
            })(weaponslot, object));

  }

})(weaponslot, object));
})(weaponslot, object)

Another approach is to create a global `THREE.Object3D()` and add your model to it, allowing for easy manipulation:

    var spaceCraft = new THREE.Object3D();
        scene.add(spaceCraft);
    var loaderModello = new THREE.OBJLoader(manager);
    var OBJPath = 'spaceCraft3.obj';

    loaderModello.load(OBJPath, function(object) {

        object.traverse(function(child) {
            if (child instanceof THREE.Mesh) {
                child.material.map = texture;
            }
        });
        var scaleFactor = 7;
        spaceCraft.scale.set(scaleFactor, scaleFactor, scaleFactor);
        spaceCraft.rotation.set(0, 9.42, 0);
        spaceCraft.model = object;            
        spaceCraft.add(spaceCraft.model);

    }, onProgress, onError);

Alternatively, you can define your model as an element of a global object like window.myobject:

window.spaceCraft = {};
loaderModello.load(OBJPath, function(object) { .....////// 
window.spaceCraft = object;
scene.add(window.spaceCraft);

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

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

What is the best way to apply a class to the currently active paragraph in Medium Editor?

Currently implementing the Medium Editor JS Clone in a project for article editing. The editor functions well, allowing element formatting with clean code. However, I am now exploring ways to add images during editing. An optimal solution would involve a ...

Display a webpage containing error messages and user input that can be sent back to the AJAX request

My form collects user information such as name, surname, etc. Here is an example of one input field: <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" value= ...

Determine the positions of two elements and adjust the array as needed

I created an array using the code below: var intestColonne = []; $('.tbi').find('tr:first th').each(function(){ intestColonne.push(($(this).children('select').val())); }); //intestColonne=intestColonne.pop(); //if this ro ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Sending both the minimum and maximum slider values to PHP using POST can be achieved by formatting the data correctly

I am attempting to transmit the minimum and maximum values to PHP using submit through a dual slider bar The static page makes a request to the server-side PHP code <?php include('server/server.php') ?> Below is the JavaScript code ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

Can a clipped object in JavaScript be duplicated on the opposite side of the screen?

Exploring javascript, I have pondered the idea of having an object clip off a screen and seamlessly appear on the other side as if the page was endless. To illustrate my concept more clearly, I have provided an image link below: https://i.sstatic.net/DCpZ ...

Stop music with one click, code in Javascript

I am encountering an issue with a set of 5 div boxes on my website. Each box is supposed to play a specific audio track when clicked, based on data attributes. However, I'm having trouble pausing the previous track when clicking on a new box, resultin ...

Combine arrays and group them together to calculate the total count of each unique value in the merged array

I have a dataset similar to the following: { "_id" : ObjectId("5a4c6fb6993a721b3479a27e"), "score" : 8.3, "page" : "@message", "lastmodified" : ISODate("2018-01-03T06:49:19.232Z"), "createdate" : ISODate("2018-0 ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

Creating animated keyframes with JavaScript and Jquery within a React environment

Currently, I am developing an animated feature within a react project. Specifically, the animation involves numerous dynamic bubbles. For each bubble, I require a rapid growth and shrink effect. Here is a snippet of how my css animation is structured: @k ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

What is the best way to ensure the current item remains in view within a div with overflow?

I am facing a challenge with a fixed height div of 400px containing a long list of items. When using prev/next links to navigate through the list, eventually the current item goes out of view. Is there a way to automatically move the scrollbar to show the ...

Working with XML files in Node.js

I'm currently running an Arch Linux system with KDE plasma and I have a 50mb XML file that I need to parse. This XML file contains custom tags. Here is an example of the XML: <JMdict> <entry> <ent_seq>1000000</ent_seq&g ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...

Is your AJAX request functional but failing to show any content on the screen?

Currently facing an issue with my quiz application's ajax request. The quiz progresses through questions and upon completion, is supposed to trigger a call to ajax.php for fetching information. I have confirmed that the ajax.php file is collecting all ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

Harnessing the power of $map in MongoDB for updating objects within query pipelines

After retrieving a list of objects from a call to db.collection.aggregate(), the results look like this: { _id: <some_id>, count: 400, results: [ { _id: 1, ... travel_guess: 0.1934042214126773, }, { _id: 2, ...