How can I add a variable to an object in Three.js?

Creating an object in Three.js and adding a variable seems like a simple task, but I'm struggling to figure it out. For instance, I want to create a cube and have it store a variable called "beenHit" that can be accessed later on.

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var newColor = new THREE.Color("rgb(12%, 6%, 0%)");
var material = new THREE.MeshStandardMaterial( { color: newColor } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
var cube.beenHit = false;

I've tried different methods and searched extensively, but I'm still unable to get it right. Any assistance would be greatly appreciated.

Answer №1

If you want to save data to an object in Three.js, you can utilize the THREE.Object3D.userData property.

cube.userData.beenHit = false;

Alternatively,

cube.beenHit = false;

using var

This method can also be effective without using var. It's important to remember that THREE.Object3D objects are essentially JavaScript objects, allowing you to store any information as long as you avoid overwriting existing Three.js properties.

Note:

Thanks to Martin's insight, it's recommended to always stick with using userData to prevent potential compatibility issues down the line.

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

Guidelines for aligning backend timer with a mobile application

I'm currently working on an app that randomly selects a user and provides them with a 15-second timer to respond. The user's app checks the database every 5 seconds to determine if they have been chosen. Once chosen, the mobile app initiates a 15 ...

Guide on bringing a function or its result from TypeScript (.ts) to JavaScript (.js)

I am working with a TypeScript file named a.component.ts import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { HttpClient } from '@angular/common/http'; @Injectable({ ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

Finding content in HTML tables using JavaScript and jQuery

I recently created a table and wanted to add a search functionality to it. I searched online, including on various forums like StackOverflow, but unfortunately, the solutions I found did not seem to work for me. Below is the code that contains both the HT ...

Using CSS to create a transition effect for fading in and out background images

I created a website with a captivating full-page background image (img/bg_start.jpg): If you hover your mouse over the central animal on the page, the current image (img/bg_start.jpg) will fade out and be replaced with another picture (img/bg_start2.jpg) ...

Optimal approach to convert a Javascript array into an object

Below is the data structure: { bill: [ { satisfy: 'true', comments: '' } ], permission_title: [ { satisfy: 'false', comments: '5' } ], final_status: [ { satisfy: 't ...

Looking for a solution to troubleshoot issues with the updateServing function in JavaScript?

I am attempting to create a function that will calculate the portion sizes for the ingredients on my website. This function is located in the Recipe.js file and appears as follows: updateServings(type) { // Servings const newServings ...

Issue with ng-true-value in AngularJS version 1.6.1 - not functioning as expected

Recently, I delved into AngularJS and followed an online tutorial that showcased how to utilize ng-true-value and ng-false-value. Here's the snippet: <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis ...

Retrieving a post variable within a function

In my current scenario, I am trying to pass a variable inside a function. The following code provides more context: <?php $id=$_POST['id']; echo " <script type=\"text/javascript\"> $(document).ready(function(){ ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Encountering issues when attempting to invoke a function from an external file in Angular4

When attempting to call a method from an external file using Angular4, I am encountering the following error: Error: ERROR in src/app/about/about.component.ts(22,9): error TS2304: Cannot find name 'checkJS'. Below is the code I am working with ...

Tips for resolving circular dependencies: When Vuex requires JS modules that are dependent on Vuex

I am facing a challenge with my Vuex store, as it imports the notifications.js module that requires access to Vuex.store.state. How can I resolve this issue? Currently, I am passing store.state as a prop to address the circular dependency. Is there a more ...

Modify the CSS preferences using an object that has been obtained

After the user selects options from a form, I am trying to update my CSS using the settings received from an object. However, I am unsure of how to implement this layout change. Here is a glimpse of my template: div class="btn btn-primary" ng-click= ...

Utilizing babel-plugin-root-import in conjunction with babel 7

Recently, I decided to dive into setting up Babel 7 for the first time. It's been a bit of a learning curve as I navigate through unfamiliar territory. While I was able to successfully install and utilize @babel/plugin-proposal-optional-chaining, I&ap ...

From converting jQuery nav-scroll to a directive in AngularJS: the power of directives

I'm struggling to convert my jQuery code into a pure AngularJS directive. I thought it should work, but I've only created one directive before. Could someone please point out what I might be doing wrong? The directive doesn't seem to have a ...

Get the shared elements from several arrays with JavaScript

Find the shared value of 12 from the given array For example: If the input is as follows: [ [12, 6],[12, 11, 9, 8, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1] ] The expected Output should be : [12] ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

When adding elements to an array from a `for` loop containing a while loop, the new values replace the existing elements in the array

Whenever I add elements to an array from a while loop nested inside a for loop, it ends up replacing the previous elements in the array. var startDate = new Date(theoreticalData[0].UpdateDateMDY); var newDate = startDa ...