"Exploring the process of animating a mesh in three.js that was generated outside of the init

Currently diving into the world of three.js, I'm eager to grasp the concept of animating a mesh that was created by a function outside of the usual init() method.

In my experiments, I've successfully managed to create and rotate a cube within the init() function and animate() function. However, once the cube is generated by a separate function outside of init(), the console throws an error stating that 'cube' is not defined.

For reference, here's a brief example: http://jsfiddle.net/mattsparrer/yqbp5hx4/10/

function createCube(size) {
    var geometry = new THREE.CubeGeometry(size, size, size);
    var material = new THREE.MeshNormalMaterial();

    cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
}

After some online research, I've come to realize that "cube" falls out of scope for the animate() function. However, I'm struggling to find the correct approach to tackle this issue. Could someone please shed some light on the proper way to achieve this?

Answer №1

This is more of a question about variable scope in JavaScript rather than Three.js.

If you define the cube variable within the init() function, it will only be accessible inside init() and not in render(). To make it available to both functions, you need to declare it outside of both.

Incorrect Usage:

function init(){
    // Defining cube within this function limits its reach
    var cube = new THREE.Mesh();
}

function render(){
    // Cube is undefined,
    // as it's only accessible within init()
    cube.rotation.y += 0.01;
}

console.log(cube); // Cube is also unavailable here.

Correct Approach:

// Define cube in global scope for accessibility in both functions
var cube;

function init(){
    // Assigns value to existing cube variable
    cube = new THREE.Mesh();
}

function render(){
    // Accesses cube within this function too
    cube.rotation.y += 0.01;
}

console.log(cube); // No errors since cube exists globally

For more insights on variable scope, check out: What is the scope of variables in JavaScript?

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

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...

I need help figuring out how to retrieve the full path of an uploaded file in JavaScript. Currently, it only returns "c:fakepath" but I need

Is there a way to obtain the complete file path of an uploaded file in javascript? Currently, it only shows c:\fakepath. The file path is being directly sent to the controller through jquery, and I need the full path for my servlet. Are there any alte ...

Adding a fresh element to an array in a mongoDB document

After researching various SO posts, I have come across different methods to achieve this task. Hence, I am curious to know which approach is considered the most preferable. Since I am instructing students, it is important for me to teach them best practice ...

Can Google Maps markers be transformed into checkboxes for use?

Is there a way to use Google Maps as a multiple locations picker, where users can select map markers and submit them through a form? ...

Extract information from an external HTML table and store it in an array

I am looking for a way to extract data from an HTML table on an external site and save it as a JSON file for further manipulation. Is there a method to retrieve table data from an external HTML site that differs from the code example provided? Additional ...

Adjust the camera in Three.js to move in a straight line towards the right

Seeking assistance with moving the 3D camera in a linear motion. The current code I am using rotates the camera around the object, but I am looking to move the camera alongside the object instead. Desired Outcome: https://i.sstatic.net/RGMxP.png Current ...

Leveraging the power of node.js, express, and handlebars to seamlessly render multiple views within a

I'm interested in finding out if there is a way to render multiple views using the res.render() function or another method. In the home.handlebars file, I currently have the following code: <h1>Home</h1> and I would like to display it i ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

Steps to invoke a function to add an element into a list

Every time a user clicks on a button, I want to generate a new tab. In this tab, when the user clicks again, I want a function to be called like: onclick('+reportname+','+report type+') onclick("'+reportname+'","'+repor ...

Type-safe Immutable.js Records with TypeScript

I'm struggling to find a suitable solution for my query. I am aiming to define data types using an interface in TypeScript, but my data consists of Immutable.js records making it more complex. Please refer to the example provided below. interface tre ...

How can you use HTML, CSS, and JavaScript to group objects with one color and then change the color of one specific object?

I have a set of 6 labels that act as buttons. When one is clicked, it changes from white to blue. If another label is clicked, the previously blue label turns white and the newly clicked one turns blue. Currently, the code below sets all labels to white b ...

I am looking to modify the background color of the columns in an Ant Design table based on whether the index of my data is even or odd

I am trying to change the background color of the columns in an Ant Design table based on the index of my data being even. Can anyone provide suggestions on how to achieve this? I have my data in a list and I want to set a condition through a loop to cha ...

The execution of my Nodejs API using the 'npm start' command is unsuccessful, resulting in the following error message

After cloning the project from GitLab, I proceeded to install node_modules using "npm install -g" and ran the "npm start" command in the terminal. However, I encountered errors as shown below: Error Cannot find module '../services/' Require ...

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

Variables for NPM Configuration

After researching the best way to securely store sensitive information, I decided to utilize the config package and environment variables for added security. Here is how I implemented this setup: Created a config directory containing two files: default.js ...

I keep getting redirected to a blank page by JS

I've created a JavaScript script that smoothly fades in the page when a user enters it and fades out when they click a link to another page. The script is working as intended, but I'm facing an issue with anchor links on the page. Whenever I clic ...

What is the best way to create a non-reactive value in Vue.js?

In my Vue.js app, I am facing an issue where an array value is becoming reactive even though I want it to remain un-reactive. The array should only be updated when a specific "refresh" action is completed. However, every time a new value is assigned to the ...

Mongoose: The aggregate method does not filter properly when using Model.field_1.field_2

Explaining a custom function: const getNotificationsForLounge = async (lounge_id) => { try { const notifications = await Notification.aggregate([ { $match: { "lounge_join_request.lounge": lounge_id, loun ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...