What's preventing me from accessing children in three.js group?

Having this particular class declaration

class GameManager {
  constructor() {
    this._activeObjects = new THREE.Group();
  }


  get randomGeometry() {
    const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1);

    return geometry;
  }

  get randomMaterial() {
    const material = new THREE.MeshBasicMaterial({
      color: "red",
      wireframe: true,
    });

    return material;
  }

  spawnCube(scene) {
  
    const newCube = new THREE.Mesh(this.randomGeometry, this.randomMaterial);
    this._activeObjects.add(newCube);
   
   
    scene.add(newCube);
  }

  animateObjects() {
    this._activeObjects.children.forEach((obj) => {
   
     obj.position.z += 1
    })

  }
}

export const gameManger = new GameManager();

Upon attempting to render and animate these cubes.

  
gameManger.spawnCube(scene);
 
(function animate() {

  gameManger.animateObjects()

 
  renderer.render(scene, camera);
  requestAnimationFrame(animate);

})();

While the cube renders correctly, the issue arises with the _activeObjects.children array only containing the added cube within the spawnCube method. Accessing it from the animateObjects method shows it as empty.

Isn't this supposed to maintain reference to the same group?

Answer №1

  createCube(scene) {
  
    const newCube = new THREE.Mesh(this.generateRandomGeometry, this.generateRandomMaterial);
    this._activeObjects.add(newCube);
   
   
    scene.add(newCube);
  }

It is important to note that by calling the .add() method twice, the object will only have one parent as an object cannot have multiple parent objects. Consequently, it will be removed from the children of the previous parent upon the second .add() invocation.

For further information, refer to the documentation:

To delve in more detail on what happens internally, check this link: https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js#L306L348

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

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

method that provides route-specific variable outputs

I have a situation where multiple routes require the same userdata from the database. Although I have a function to verify if the user is logged in, this function does not return the user variables. Here is an example route: app.get('/template', ...

What causes $(this) to stop functioning post successful execution?

Here are the code snippets I'm currently working with: $(this).removeClass('page larger').addClass('current'); $(this).siblings().removeClass('current').addClass('page larger'); Interestingly, when I try to pl ...

I am experiencing issues with utilizing Array Filters in my Node.js backend when working with MongoDB

Utilizing it with Node.js in my backend. Encountered the following query: db.conversations.update( { convoId: convoId }, { $set: { "ids.$[elem].read" : true } }, { arrayFilters: [ { "elem.id": userId } ] }, (err, data) => { if(err) { ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

What is the best way to add external javascript files to bookmarklets?

I have been developing a CDN for a collection of scripts that I created for my job. Previously, I had to distribute these scripts individually and each user would have to download and install them on their own computer. Now, I am transitioning them to an A ...

Implementing Firebase with NextJS to append objects to a nested array

I'm currently working on my project using nextjs and firebase. The project concept revolves around a hybrid project management system where users can create projects with multiple boards to organize and store tasks: Board UI This is how I plan to sav ...

Is it possible to retrieve the value of a particular field from a table?

My goal is to create a table that displays data about various users awaiting admin approval. Each row represents a specific user, and when the approve button on a particular row is clicked, I want to open a new window displaying detailed user information f ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

Exploring the intricacies of managing nested data in a Firebase Database (web)

I understand this question may have similarities to others already asked, so my apologies in advance. I am seeking a clear, up-to-date solution that aligns with my expectations. https://i.sstatic.net/dQ9ih.jpg If I have an object labeled "Item One", how ...

I am encountering an issue where my express.js server is not successfully processing the data sent from my react native

I have set up an API object in React Native with the following code: import axios from "axios"; import AsyncStorage from "@react-native-async-storage/async-storage"; const instance = axios.create({ baseURL: "localhost url here&q ...

Tips for iterating through a nested object in JavaScript with the forEach method

Here is my answer to the query. In this snippet, results represents a freshly initialized array. The object address nests within the user object. response.data.forEach(user => { results.push({ id: user.id, name: user.n ...

Leveraging the power of ajax to securely save information in a database with the web2py framework

Struggling with a major issue here. I have set up the following tables db.define_table('post', Field('user_email', default=auth.user.email if auth.user_id else None), Field('title', 'strin ...

Angular foreach method encounters a syntax issue

When I use the getTotal.getValues() function to make a server call that returns values like "one", "two", "three" up to "nine", I am able to print them using console.log(res). However, I am facing an issue where I cannot push these returned values into t ...

Unleashing the Power of Object Destructuring in React Hooks

Here is a straightforward code snippet: import React from "react"; import { useForm } from "react-hook-form"; export default function App() { const { register, formState: { errors }, handleSubmit } = useForm(); return ( < ...

Tips for making Angular automatically generate the property in HTML when employing the bind feature

When using property binding in Angular, I noticed that the property is not created in the HTML unless I directly write the value in the code. For example, in a StackBlitz demonstration with a 'button' component that changes color based on the typ ...

Creating a clickable map for a PNG image: Step-by-step tutorial

My goal is to create a interactive map similar to this one. Click here for the image ...

Having trouble with finding the correct object in an array of objects using indexOf and splice()?

Here is an example of an array of objects: "followers": [ { "id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01", "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece", "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda", ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...