Exploring the Beauty of Cubes within Three.JS

Recently delving into the world of THREE.js, I've set out on a mission to create a cube composed entirely of cubes, much like this example:

https://i.sstatic.net/hQRoB.jpg

To achieve this, I've structured my 3D array as follows:

[[grid][line,line][[cube,cube],[cube,cube]]]
. Essentially, the cube consists of grids, which consist of lines, and each line is made up of individual cubes. Below is the code snippet:

function lineOfMeshes(w, g) {
  var cubes = [];

  for (var i = 0; i < w; i++) {
    cubes.push(new THREE.Mesh(geometry, material));
    cubes[i].position.x += i * g;
  }
  //console.log("LINE:" + cubes);
  return cubes;
}

function gridOfMeshes(w, g) {
  cubes = [];
  for (var line = 0; line < w; line++) {
    cubes.push(lineOfMeshes(w, g));
    for (var cube = 0; cube < w; cube++) {
      cubes[line][cube].position.z += line * g;
    }
  }
  //console.log("GRID: " + cubes);
  return cubes;
}

function cubeOfMeshes(w, g) {
  cubes = [];

  for (var grid = 0; grid < w; grid++) {
    cubes.push(gridOfMeshes(w, g));
    for (var line=0;line<w;line++) {
      for (var cube = 0; cube < w; cube++) {
        cubes[grid][line][cube].position.z += line * g;
      }
    }

  }
  //console.log("CUBE"+ cubes);
  return cubes;
}

//var container = document.getElementById("3dcontainer");

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

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

var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
var geometry = new THREE.BoxGeometry(); //object that contains all the points and faces of the cube
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); //material that colors the box
//var cube = new THREE.Mesh(geometry, material); //a mesh is an object that takes a geometry and applies a material to it

///////////////////////////////////////////////////////

let gridWidth = 5;
let gridGap = 3;

cubes = cubeOfMeshes(gridWidth, gridGap);

cubes.forEach(grid => {
  grid.forEach(line => {
    line.forEach(cube=>{
      scene.add(cube);
    })
  });
});

camera.position.z = 5;

///////////////////////////////////////////////////////

//render loop
function animate() {
  requestAnimationFrame(animate);

  controls.update();

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

Unfortunately, upon running the code, I encountered the following error:

 index.js:31 Uncaught TypeError: Cannot read property 'position' of undefined
    at cubeOfMeshes (index.js:31)
    at index.js:65

I'm perplexed by this issue, as I've double-checked my indexing method. Any insights would be greatly appreciated. Thank you in advance.

Answer №1

The reason for the issue in your code is that you forgot to use const, let, or var before cubes in both gridOfMeshes and cubeOfMeshes. This means they are essentially the same variable and end up being overwritten.

Keep in mind that if you include

'use strict';

at the beginning of your JavaScript file, any such errors will be highlighted in the JavaScript console with the message:

Uncaught ReferenceError: cubes is not defined
    at cubeOfMeshes (js:40)
    at js:80

Additionally, using a text editor like Visual Studio Code along with the eslint plugin can be beneficial. It may require some configuration but once set up, it will flag these types of errors in real-time while you code.

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

How can we avoid re-rendering the same component repeatedly when using React Router v6?

As a beginner in react, I'm facing an issue with preventing components from re-rendering when navigating to a different page. Specifically, I want to display only text on my Signup and Login pages, but the Navbar keeps re-rendering every time I switch ...

Error: We are facing an issue with new.mongoose.Schema as it is not functioning properly and

I am experiencing an issue with my product.js file. It keeps throwing an error about an unidentified identifier, and whenever I try to fix one problem, another one pops up. I have been struggling to locate the root cause of this error. ...

Preloading videos for optimal performance on mobile devices

Looking for a solution where 4 MP4/video files, each 5MB in size, can be played consecutively without gaps between them on all browsers and devices. Preferably not looking for a solution involving the replacement of video source files. The current approac ...

How can we map a promise that resolves to foo to a new promise that resolves to bar?

I am working on a function that uses an XMLHttpRequest to retrieve data and returns a promise with the response. But now I want to modify it so that the promise only contains a specific string from the response. Instead of resolving to response = {status ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Transforming a collection of nested objects from Firebase into an array in JavaScript/Typescript

In my Ionic3 / Angular4 application, I am utilizing Firebase. The structure of the data in Firebase Realtime Database is as follows: Using the TypeScript code below, I am fetching observable data from Firebase... getDishesCategories(uid: string) { ...

How can I check and add contacts on Telegram?

Assistance needed: I have 40,000 mobile numbers and I need to perform the following tasks: Verify if these numbers have a Telegram account Add these accounts to the contact list Can anyone provide advice on how to accomplish this? Perhaps with examples o ...

Working with Firestore database in React Js may result in an infinite loop

I have connected my React JS app to Cloud Firestore and I am facing an issue with displaying the objects in my JavaScript file. Even though I only have one object in Firestore, it seems to be reading in a loop and I can't seem to identify the cause. ...

Executing an animation in Angular 4 using a Directive

There's an ongoing issue on the repository here, but I wanted to see if anyone here could help as well. I am trying to programmatically trigger an animation from a Directive. However, when using Renderer.animate, I receive the following error: Rende ...

Improving callback functions in Express/NodeJs for a more pleasant coding experience

function DatabaseConnect(req, res) {...} function CreateNewUser(req, res) {...} function ExecuteFunctions (app, req, res) { // If it's a POST request to this URL, run this function var firstFunction = app.post('/admin/svc/DB', func ...

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

Store the active tab in AngularJS with Bootstrap to easily remember and display

After creating a basic AngularJS application with the Bootstrap directive, I noticed that some of my pages have tabs. The issue arises when I am on a tab other than the first one and click a link to navigate to another view. Upon returning (using either th ...

Utilizing ag-grid with Vue.js: Implementing TypeScript to access parent grid methods within a renderer

I've integrated ag-grid into my project and added a custom cell renderer: https://www.ag-grid.com/javascript-grid-cell-rendering-components/#example-rendering-using-vuejs-components Although the renderer is working well, I'm facing an issue whe ...

Adjusting the drag mouse position in jqueryUI

I'm currently working on coding a Lockscreen design inspired by ios8. I want to create a draggable element that only moves along the x-axis. $( "#IDlsDragable" ).draggable({ axis: "x" }); .lockscreen { position:fixed; top:0px; left:0px; wid ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

Clicking outside of Bootstrap Modal inputs causes them to lose focus

Currently, I am tackling a challenge involving 2 bootstrap modals located on the same page with Bootstrap version 2.3.2. A frustrating issue that has arisen is that whenever either modal appears, the first time you click on any of the inputs within the mo ...

Discover the secrets to acquiring cookies within a Next.js environment

I am currently working with Next.js and attempting to retrieve a cookie value. Below is the code I have written: import cookie from "js-cookie"; export default function Home({ token }) { return ( <div className="flex flex-col items ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

What prompts JQuery to interpret ajax responses as xml in Firefox?

let url = "/MyApp/pspace/filter"; let data = JSON.stringify(myData); $.post( url, data, function(response, textStatus, jqXHR) { console.log("response: " + response); }, "json" ); In actuality, the expected type of response is a JSON string. ...

The function str.split() is dividing the text based on individual letters rather than the specified delimiter

I am facing an issue where the string of tags retrieved from firebase needs to be split by ',' and stored in the data() for rendering. The firebase snapshot data is correctly formatted after splitting when viewed in the console like this: "t ...