Error message "Unable to access property 'rotation' of an object that does not exist - Three.js"

I'm currently facing an issue where my code is executing as expected, but there are two errors popping up in the console saying "Cannot read property 'rotation' of undefined". It's puzzling because both variables are defined globally. Is there something I might be overlooking? (I switched to using TextureLoader() since ImageUtils.loadTexture() has been deprecated).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <title>Three.js</title>
    <style>
        body{
            margin: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r80/three.js"></script>
    <script src="js/OrbitControls.js"></script>
    <script>

        //GLOBAL VARIABLES
        var scene, camera, renderer, cameraControl, earthMesh, cloudMesh;

        function init(){

            //scene
            scene = new THREE.Scene();

            //renderer
            renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setClearColor('#000', 1.0);
            renderer.shadowMap.enabled = true;

            //camera
            camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 1000);
            camera.position.x = 35;
            camera.position.y = 36;
            camera.position.z = 33;
            camera.lookAt(scene.position);

            //earth mesh
            var sphereGeometry = new THREE.SphereGeometry(10, 60, 60);
            var sphereMaterial;
            var sphereMaterialLoader = new THREE.TextureLoader();
            sphereMaterialLoader.load(
                'images/earth.jpg',
                function(earthImage){
                    sphereMaterial = new THREE.MeshBasicMaterial({
                        map: earthImage
                    });
                    earthMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
                    earthMesh.name = 'earth';
                    scene.add(earthMesh);
                    render();   
                }
            );

            //cloud mesh
            var cloudGeometry = new THREE.SphereGeometry(sphereGeometry.parameters.radius * 1.02, 
                sphereGeometry.parameters.widthSegments, sphereGeometry.parameters.heightSegments);
            var cloudMaterial;
            var cloudMaterialLoader = new THREE.TextureLoader();
            cloudMaterialLoader.load(
                'images/clouds.png',
                function(cloudImage){
                    cloudMaterial = new THREE.MeshBasicMaterial({
                        map: cloudImage
                    });
                    cloudMaterial.transparent = true;
                    cloudMesh = new THREE.Mesh(cloudGeometry, cloudMaterial);
                    cloudMesh.name = 'cloud';
                    scene.add(cloudMesh);
                    render();
                }
            );

            //camera control
            cameraControl = new THREE.OrbitControls(camera);

            document.body.appendChild(renderer.domElement);
            render();
        }

        function render(){
            renderer.render(scene, camera);
            earthMesh.rotation.y += -0.001;
            cloudMesh.rotation.y += 0.0005;
            cameraControl.update();
            requestAnimationFrame(render);
        }

        //initialize scene/render
        window.onload = init;

    </script>
<</body>
<</html>

Answer №1

It appears that the initialization of earthMesh is happening asynchronously within your cloudMaterialLoader.load() function -- it is crucial to be cautious because when render() is first called, earthMesh may not have finished loading yet, resulting in it being undefined.

There are several ways to address this issue, such as delaying the render() call until earthMesh has fully loaded, or incorporating a check for the status of earthMesh within the render() function, among other creative solutions.

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

Store the JSON file for future reference to extract additional information from it at a later time

I am struggling to update my JSON file with new data and retrieve that updated data when needed. Currently, whenever I try to access any information from the JSON file, it shows the same data as the last time I saved it manually. I have made some changes ...

Electron Developer: "An issue has occurred within the primary process - Callback function missing"

My Electron application runs smoothly when launched from the command line with npm start. However, I am now looking to distribute the application as user-friendly installers for Mac/Windows/Linux. To achieve this, I am utilizing Electron-Builder for packag ...

Obtain a specific portion of text from a string that resembles a URL

$("#index-link")[0].search = "?isNameChecked=False&isDateChecked=False&isStatusChecked=True" Is there a way to use jQuery to identify whether isStatusChecked is set to true or false in the given string? ...

Accessing factory in controller using AngularJS

Currently, I am utilizing the following link to integrate requirejs with angularjs: https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 My question is regarding how to use a service function that is defined ...

switching the color of a path in an SVG when hovering over a

In the midst of working on SVG, I'm trying to implement a color change effect upon hover. The desired functionality is such that when hovering over the .business div, the color of the SVG business path should also change accordingly as specified in th ...

JavaScript appendChild method not functioning properly with dynamically created image elements in JavaScript code

I recently encountered an issue while working on a website project. I was trying to create an img element using JavaScript, but ran into a problem when I tried to add the src attribute and then use the appendChild function. I'm unsure if I am missing ...

Modify a class attribute within a function

I need to modify the this.bar property within my class when a click event occurs. The issue is that the context of this inside the click function is different from the this of the class. export class Chart { constructor() { this.bar; } showC ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

Enhancing arrow cone spin with ThreeJs

My arrow function is supposed to connect pick and place points using QuadraticBezierCurve3 and ConeGeometry, but the rotation of the cone doesn't align perfectly with the curve as shown in the snippet below! I'm seeking advice on how I can enhan ...

The Jquery map function is not returning selected options, always returning empty values. It seems to be avoiding the variable, although it functions properly on jsfiddle. There are

RESOLVED: Final solution: http://jsfiddle.net/AcfUz/220/ *applied the selector mentioned in the selected answer and adjusted the console.log value to appear before the text input, where the chosen options were supposed to be displayed, and voila--it&apo ...

Stop unauthorized access to php files when submitting a contact form

I have implemented a contact form on my HTML page that sends an email via a PHP script upon submission. However, when the form is submitted, the PHP script opens in a new page instead of staying on the current page where the form resides. I have tried usin ...

Scrapy-splash seems to be encountering difficulties in extracting elements during the scraping process

My attempt to extract data from this Why is Splash not working here? Does anyone have a solution for me? Your assistance will be highly appreciated! ...

Tips for invoking the setState method via an onClick event the ES6 way

class BlogPost extends React.Component{ //getInitialState constructor(){ super(); this.onLike = this.onLike.bind(this); this.state = { like :0 } } onLike(){ this.setState({ li ...

AngularJS - A pagination demonstration incorporating intelligent logic inspired by Google's approach

I struggled to implement a paging solution that I came across online. The issue seems to be related to the timing of function calls, specifically how the setPage function is triggered before all data is retrieved, causing it to not properly determine the t ...

What are some ways to incorporate a Three.js script within a Vue project?

I encountered a challenge while trying to incorporate a three.js script written in vanilla JavaScript into a Vue project. The script utilizes the three function objLoader to import an object from a local file. While the script functions accurately in vanil ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...

Error: React is throwing a SyntaxError because a ")" is missing in the argument list

While working on a React-typescript project using Vite, I encountered an issue where my page was displaying blank and showing the error : Uncaught SyntaxError: missing ) after argument list (at main.tsx:6:51) This error was found in the main.tsx file : im ...

Updating a React JS State using a Parameter

Is it feasible to develop a function that accepts a parameter (either a string of the state name or the actual state) and then assigns the state related to the parameter? SetState(x) { // Suppose x can be any state we have already defined (it sh ...

Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any as ...

Pairing strings with arrays

I'm trying to compare elements in two arrays and see if there are any matches. However, I can't seem to get it working correctly. let name; let list = ["Kat", "Jane", "Jack"]; // sample array let input = ["Hey", "i'm", "Jack"]; if (input.fo ...