There was an error: Unable to access the 'rotation' property of an undefined object

Currently learning three.js and following the documentation step by step. As I progress, I reach the following code snippet:

                 function animate(renderer, scene, camera, cube) {
                    requestAnimationFrame( animate);
                    cube.rotation.x += 0.01;
                    cube.rotation.y += 0.01;
                    renderer.render( scene, camera );
                 }

                 function init() {
                   var scene = new THREE.Scene(); //setting up the scene
                   var camera = new THREE.PerspectiveCamera(75, window.innerWidth / 
                   window.innerHeight, 0.1, 1000);//configuring the camera; 75= fov is the extent of the scene 
                   that is seen on the display at any given moment; the ratio is the aspect ratio;

                   var renderer = new THREE.WebGLRenderer();//initializing the renderer;
                   renderer.setSize(window.innerWidth, window.innerHeight);
                   document.body.appendChild(renderer.domElement);

                   var geometry = new THREE.BoxGeometry(1, 1 , 1); //this object contains all 
                   the points;
                   var material = new THREE.MeshBasicMaterial({ color:0x00ff00 }); //applying color to it;
                   var cube = new THREE.Mesh( geometry, material); //creating an object that takes a geometry 
                   and applies a material to it;
                   console.log(cube);
                   scene.add(cube);
                   camera.position.z = 5; // moving the camera slightly away from the cube,

                   animate(renderer, scene, camera, cube);
                 }
                   window.onload = init;

I am attempting to load an object and then rotate it, however, I encounter an error. The object loads successfully but errors are continuously being reported. I've delved into this issue and suspect it may be related to asynchronous loading of objects, yet I cannot fully grasp how this pertains to my scenario.

Answer №1

After thorough research, it has come to light that the issue could be related to the asynchronous loading of objects

It's important to note that the problem is not actually caused by asynchronous loading, especially since there are no assets being loaded from a backend.

The root of the issue lies in the fact that the cube variable is being declared inside the init() function, making it invisible in the animate() function. To fix this, it is necessary to declare cube outside of both functions.

Answer №2

To reiterate what @Mugen87 said, you simply need to move the variable declaration outside of your function definition.

var cube = null

function animate(){
  // ...
}

function init(){
  // ...
  cube = new THREE.Mesh( geometry, material );
  // ...
}

In JavaScript, variables are functionally scoped, meaning they are only accessible within the function in which they are declared (including any functions defined within that scope).

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

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

Managing ajax requests timeouts while abiding by the browser's connection limitations

Encountering an issue with ajax requests and fixed timeouts, I've resorted to using this straightforward code snippet: $.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something ...

What is the reasoning behind excluding any JavaScript code between the <script> tags when our intention is solely to incorporate an external JS file?

It's puzzling to me why the author of the "Javascript & Jquery: the missing manual , second edition" recommends the following sentence: When including the src attribute to connect to an external JavaScript file, avoid placing any JavaScript cod ...

Ways to invoke a JavaScript function via a hyperlink. Various techniques to achieve this task

I want to create a div with the id of slider, and I am looking for a way to animate or hide it when a link is clicked. Specifically, I would like to toggle it open and close using a link. Javascript solution <script type="text/javascript"> ...

Invoke the identical function in between two functions that make asynchronous AJAX calls

I seem to be a little lost at the moment. The code snippet below illustrates my intent, which is to use the insertChilds() function to insert child elements in the DOM in a cascading manner (or at least that's what I'm aiming for...). The challe ...

Understanding the reading of Java Class List in Vue Js

As a beginner in Front-end development, I am trying to figure out how I can use Vue.js to read a Java class List. Specifically, I have a Java class that includes a list of fruits and I want to be able to display this list on the UI using Vue.js: public c ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

How to rotate a SVG transformation matrix around its center point

CSS .square { background-color: green; height: 40px; width: 40px; } JS var square = { sizeReal : { "width": 40, "height": 40 } , position : { "x": 100, "y": 100 } }; $(". ...

Is there a noticeable distinction or significant benefit between using auth.signOut() and signOut(auth)?

When it comes to logging out with Firebase, is there a significant difference or advantage between using auth.signOut() or signOut(auth)? This concept also applies to other authentication processes like logging in and signing up. The Firebase documentation ...

Combining Angular JS 1 and Laravel 5.2 for seamless integration

Currently, I am in the process of setting up Angular JS 1 with Laravel 5.2 by installing the necessary dependencies using npm. After installation, a node_modules folder was created alongside the app directory. My primary concern is whether it is recommend ...

Stop accidental clicks during dragging

I am currently utilizing Three.js to exhibit a 3D model that allows users to manipulate the camera by dragging and click on objects to zoom in. However, I am encountering an issue where the system registers a click and drag as a click, triggering the anima ...

Learn how to update a form dynamically using the Ajax.BeginForm feature

I am currently working on updating a form within my application using Ajax.BeginForm. The update process is functioning correctly, however, upon executing the function in the controller, it redirects to a view with the controller function name displayed. ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

What is the process of assigning a string from an external PHP file to a JavaScript variable?

Recently, I've been experimenting with reading data from an external PHP file using Ajax. My goal is to store this data in a Javascript variable, but I'm unsure if my current approach is correct. Should I define the variable within the Ajax brack ...

Express.js Failing to Send Response Following POST Request

This is the function I have on the back end using express: // Function to register a new user exports.register_user = function(req, res) { var portalID = req.body.portalID; var companyName = req.body.companyName; var password = req.body.passwo ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

Setting initial values for an object in JavaScript

I am currently seeking a method to store predefined values in a separate file for populating my function: Here is my function in index.js: const Modes = (array) => { return { name: array.name, funcionarioIncrease: array.funcio ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

Misunderstandings between HTML and CSS

Can someone please clarify how the functionality of the active-slide class? Code: <div class="slider"> <div class="slide active-slide">..</div> <div class = "slide slide-feature">..</div> <div class = "slide">..</di ...