How come I'm having difficulty adjusting the size and positioning of a mesh in three.js?

After inserting a mesh into the scene, I encountered an issue whenever I attempted to adjust its scale or position. An error message stating that the mesh is null would consistently pop up.

  mesh2.position.set(0,0,-5);
  mesh2.scale.set(0.2, 0.3, 0.2);

Uncaught TypeError: Cannot read property 'position' of null

For further details, you can visit testing2.site44.com.

I am seeking assistance as I have invested countless hours attempting to resolve this issue.

function init()
{
    var scene = new THREE.Scene();

    var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
    var renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setClearColor(new THREE.Color('#005b96'), 1)
        renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        document.body.appendChild( renderer.domElement );
        renderer.domElement.id = "canvas_threeJS";

    //Add camera to the scene
    var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR =1000;
    var camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
        camera.position.set(0,3,8);
        camera.lookAt(new THREE.Vector3(0,0,-5));
        scene.add(camera);

    //Add ambient light
    var ambientLight = new THREE.AmbientLight("#6497b1");
        scene.add(ambientLight);

    //Handle window resize
    //Add main light
    var light = new THREE.PointLight("#b3cde0",.6);
        light.position.set(-5,13,-1);
        scene.add(light);


    var mesh2 = null;
    var loader = new THREE.JSONLoader();
    loader.load('assets/models/spaceship001.json', function(geometry) {
        mesh2 = new THREE.Mesh(geometry);
        scene.add(mesh2);
        console.log("done loading model");
        });

      mesh2.position.set(0,0,-5);
//    mesh2.scale.set(0.2, 0.3, 0.2);


    //Start position of a level group
    var levelSpawn = -100;

    //Get visible width at levelSpawn position
    var vFOV = camera.fov * Math.PI / 180; 
    var height = 2 * Math.tan( vFOV / 2 )*levelSpawn; 

    var aspect = window.innerWidth / window.innerHeight;
    var width = height * aspect;

    //Start rendering
    update();

    function update()
    {

        //Update 3D scene
        renderer.render( scene, camera );

        //Continue rendering
        requestAnimationFrame( update );
    }


}

Answer №1

The issue stems from the asynchronous nature of JavaScript. It's essential to familiarize yourself with this concept based on your background. One solution is to insert a

console.log("setting scale and position")
right above or below those specific lines. Upon doing so, you'll observe that the position and scale are being adjusted prior to the mesh loading.

To address this issue, ensure that you adjust the position and scale within the callback function passed to the load function directly beneath the

console.log("done loading model");
line.

For a deeper understanding, consider delving into JavaScript Promises.

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

When an icon is hovered over in Vue, a text box popup will be displayed

Working on a personal project that requires obtaining the status of all devices within a unit. The status, along with the device name, is returned in an array from the function deviceStatus(). If all devices are currently marked as ON, the home icon next t ...

Display the input value in AngularJS in a customized format without changing the format in the model

When receiving an integer indicating a duration in minutes, I want to display it as hours or days if it exceeds a certain value. The ng-model should still keep the value in minutes so that any user changes are reflected accurately. For example: Reading & ...

What is the reason behind delaying the assignment of a global variable right after the creation of a callback or listener function, such as in the case of asynchronous messaging using

Just starting out with writing Firefox add-ons and learning as I go. Recently stumbled upon this code snippet on MDN: var tabs = require("sdk/tabs"); tabs.on('activate', function(tab) { var worker = tab.attach({ contentScript: 'self. ...

Performance issues with jquery addClass and removeClass functions observed in Internet Explorer 11

I am currently working on an application that monitors nodes within a cluster, and I have created a visual state example to demonstrate this. Each small box in the grid represents a node, and when hovering over a node, the rest of the nodes in that particu ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

Retrieve dimensions of text using the <a-text> component in Aframe

Having issues retrieving the height and width of an aframe text component in a custom aframe component. The text is visible in the scene and I can log the 'geometry' and 'material' properties. However, the 'layout' property is ...

Displaying entries of input data

I have an application that includes a modal window with filters, but I am looking to add another type of filter. However, I am struggling with implementing it in React and would appreciate any help with the code or recommended links. Essentially, I want t ...

The binding on an AngularJS page is only retained by the final directive applied

Having a few directives that need to be reused as elements, I've decided to implement scope isolation. Each directive is associated with its own controller, which retrieves data from MongoDB based on the URL. The issue I'm facing is that only th ...

modify the navigation when router events are triggered

Is there a way to modify the destination route after the router events have been triggered in an Angular app? I am trying to implement a functionality where if the user clicks the browser back button, the navigation is redirected to the home page. However, ...

Using an Ajax call within an event handler function

After spending a full day attempting to execute an AJAX call within an event handler function, I've tried various combinations of when(), then(), and done(), as well as setting async: false. However, I keep encountering undefined errors despite my eff ...

Transferring information from a component that includes slot content to the component within the slot content

This task may seem complex, but it's actually simpler than it sounds. I'm struggling with the correct terminology to enhance the title. I need to transfer data from a component that includes slot content to that slot content component. In partic ...

The Sprite.render Depth attribute is not compatible with three.js

Here is the code snippet: var sprite = new THREE.Sprite(material); sprite.renderDepth = 10; The renderDepth setting specified above is not valid for sprites. Do you know how to address this issue? ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

An illustration of webpack 4 and Vue.js compatibility tailored specifically for Internet Explorer 11, featuring multiple entry points

This feels like déjà vu - yet another issue with Internet Explorer and webpack. I'm on the brink of deploying my project when IE 11 decides to mess everything up. I thought I had covered all bases with babel-polyfill and the latest versions, but of ...

Tips for creating a Material UI (next) dialog with generous top and bottom margins that extend off the screen

I am encountering a challenge with the layout. What am I looking for? I need a modal dialog that expands vertically, extending beyond the screen, centered both horizontally and vertically, with minimal margin on the top and bottom. Is this feature not d ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

Using JQuery to automatically scroll and anchor to the bottom of a dynamically populated div, but only if the user doesn't

I am attempting to achieve the functionality of automatically scrolling to the bottom of a div with the ID #chat-feed. The overflow for this div is set to auto, and I want it to remain at the bottom unless a user manually scrolls up. If they do scroll up, ...

When making an AJAX request, ensure the response is in JSON format with individual properties rather than as a single

Here's an example of an AJAX request with JSON dataType: JavaScript: function checkForNewPosts() { var lastCustomerNewsID = <?php echo $customers_news[0]['id']; ?>; $.ajax({ url: "https://www.example.com/check_for_n ...

Obtain informative shader construction logs in ThreeJS

Whenever my ThreeJS custom shaders contain errors, I receive the enigmatic INVALID_OPERATION message in the JS console while rendering: WebGL: INVALID_OPERATION: useProgram: program not valid Is there a way to generate a more informative log, similar to ...

You can utilize the Toggle Button to alternate between multiple classes, not just two

Currently, I am learning Java with Spring Boot and Thymeleaf. While creating some views, I faced a challenge. Initially, I wanted to create a toggle button for "Pending" and "Received". However, now I am attempting to add the option "Cancelled", but I have ...