Troubleshooting positioning glitches in three.js using a for-loop

I'm currently working on a function to randomly place imported clouds, but I've run into an issue where all the clouds end up in the same position. Although I've randomized the position, they still appear stacked on top of each other. Here's the code snippet in question:

loader.load('/clouds/clouds1/scene.gltf', function (clouds1) {


  var clouds1array = []
  function addClouds1(){

    for (var i = 1; i < 10; i++) {
      const clouds1Mesh = clouds1.scene
      const clouds1Position = clouds1Mesh.position
      clouds1Position.x = Math.random() * 10
      clouds1Position.y = Math.random() * 10
      clouds1Position.z = (Math.random() - 0.5 ) * 300

      clouds1Mesh.scale.setX(0.05)
      clouds1Mesh.scale.setY(0.05)
      clouds1Mesh.scale.setZ(0.05)
      
  
      scene.add(clouds1Mesh)
      clouds1array.push(clouds1Mesh)
  
      
    }
    
  }

  
  addClouds1()
  
})

edit: clouds1.scene structure is this:https://i.sstatic.net/iNY4d.png

Despite trying different approaches offered by others, the issue persisted. The third child at the end holds the mesh, and I attempted using that in the scene.add() function, but encountered errors.

edit: Issue resolved! Moving the for loop outside the load function fixed everything.

 for(let i = 0; i < 30; i+= 3)

loader.load('/clouds/clouds1/scene.gltf', function (clouds1) {

 
 const cloud = clouds1.scene

 const child1 = clouds1.scene.children[0].children[0].children[0].children[2].children[0]


 child1.material = new THREE.MeshStandardMaterial({ emissive: 'white', emissiveIntensity: 0.5})

 cloud.scale.set(0.05, 0.05, 0.05)

 cloud.position.x = (Math.random() - 0.5) * 500
 cloud.position.y = (Math.random() + ((Math.random() + 20 ) + 70))
 cloud.position.z = (Math.random() - 1) * 500

 cloud.rotation.x = Math.random()
 cloud.rotation.y = Math.random() 
 cloud.rotation.z = Math.random() 



 scene.add(cloud)


})

Answer №1

The data retrieved by the GLTFLoader, stored as clouds1, represents a generic object that contains valuable information. Specifically, within this object, you can access clouds1.scene. This particular property, clouds1.scene, refers to a single instance of a Scene object. If your GLTF model includes 10 clouds, then clouds1.scene will have 10 child elements. To process these children effectively, you must iterate through them using the following code snippet:

loader.load('/clouds/clouds1/scene.gltf', function (clouds1) {

  var clouds1array = []

  const clouds1Children = clouds1.scene.children

  for (var i = 1; i < 10; i++) {

    const clouds1Mesh = clouds1Children[i]
    const clouds1Position = clouds1Mesh.position
    clouds1Position.x = Math.random() * 10
    clouds1Position.y = Math.random() * 10
    clouds1Position.z = (Math.random() - 0.5 ) * 300

    clouds1Mesh.scale.setX(0.05)
    clouds1Mesh.scale.setY(0.05)
    clouds1Mesh.scale.setZ(0.05)
      
    scene.add(clouds1Mesh)
    clouds1array.push(clouds1Mesh)
  
  }
  
})

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 I utilize the replace function in Angular to swap out a character?

I am attempting to change the characters { and } in an HTML string to {{ and }}. However, when using the replace function, I encounter the following error: $scope.selectedtemplate.template.replace is not a function Below is my code: $scope.selectedte ...

Error: Unable to access 'push' property of null object in Next.js Link

Utilizing Vite to develop a reusable component has led to an error upon publishing and reusing it: TypeError: Cannot read properties of null (reading 'push') The code for the component is as follows: import React from "react"; import ...

How can I prevent SweetAlert from automatically focusing when it first opens?

I recently integrated SweetAlert into my project and customized the buttons like this: swal("A wild Pikachu appeared! What do you want to do?", { buttons: { cancel: "Run away!", catch: { text: "Throw Pokéball!", value: "catch", ...

jQuery - Creating an organized hierarchy list

My website's DOM structure is shown below: <ul> <li id="Browse"> Browse <ul id="browse-one"> </ul> </li> </ul> At the bottom of the page, my jQuery script looks like this: $("#Brow ...

What is the best way to send an array and file in the same AJAX request?

When attempting to send both an image file and an array through my AJAX request to a PHP script, I encountered an issue where either the array or the image file doesn't appear. The problem seems to stem from the specific lines that need to be added to ...

Issue with updating overall expenditure functionality

I'm currently in the process of developing a straightforward shopping cart with the help of simpleCart.js. Up until now, I've managed to successfully showcase items, add them to the basket, and proceed to checkout. However, my next challenge inv ...

Getting data from an Ajax call

I am struggling to find a solution for retrieving data from a processing script into a Request page using Ajax and PHP. The issue I am facing is shown in the error message below: SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the J ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

One common issue is being unable to target input[type=file] when multiple forms are present on a page using JavaScript

Question: I have multiple dynamic forms on a web page, each with a file input field. How can I specifically target the correct file input using $(this) in JavaScript? Here is an example of one of my forms: <form enctype="multipart/form-data" action="c ...

Ways to enlarge a YouTube thumbnail upon loading using JavaScript

I recently found a solution to my question on how to prevent YouTube videos from repeating even when different embedded codes are used. I have a specific need to resize the thumbnail image of my YouTube video to width:146px and height:124px when the page l ...

"Enhance your database by incorporating HTML link clicks through AJAX integration with PHP and MySQL

After browsing through similar questions and attempting to implement it on my website, I'm facing an issue where the expected functionality is not working as intended. When users click on a link, there is no response in the console, and the database r ...

Using a for loop to populate labels with text

If I have 10 labels named "Label1", "Label2", "Label3".... up to "Label10", is there a way to create a for loop where I can assign text based on each label's number? For example, Label1.Text will display "1", Label2.Text will display "2", and so on u ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

Issue with clicking and toggling classes in Javascript

I am experimenting with creating a simple 3 slide slider, but I am facing some issues with the JavaScript. My goal is to have the current slider slide out and the selected one slide in when clicking on the slider color. I'm attempting to achieve this ...

Modifying an object's label based on a particular value using JavaScript

In my current project involving React.js charts, I am looking to organize data by month. In Django, I have set up a view to display JSON containing the total events per month in the following format: [ { "month": "2022-06-01T00:00:0 ...

Developing a breakout-style game using three.js: finding the end of the game board

As I dive into learning Three.js by creating a game, I've encountered a challenge with outdated resources and the constantly changing library. Currently, I can move my paddle with my mouse and launch the ball on click, but I'm struggling to preve ...

Prevent the reloading of the page by utilizing Ajax technology when submitting a form in Laravel

I'm facing a challenge with processing a form submit using ajax instead of Laravel to prevent page reloads. Unfortunately, it's not working as expected and I'm struggling to figure out the issue. Despite researching numerous examples online, ...

The addClass() and removeClass() functions in Jquery are not functioning correctly

$('.push').each(function(){ if($(':first-child',this).hasClass( "activex" )){ $(this).off().off('click').on('click',function(){ var a = $(this).attr('id'); $.ajax({ type: "POST", ...

When using the `array.join` method with nested arrays, it does not automatically include spaces in the output

function convertArrayToString(arr) { // Your solution goes here. let str = arr.join(", "); return str; } const nestedValues = [5, 6, [7], ["8", ["9", ["10" ]]]]; const convertedString = convertArrayToString(nestedValues); console.log(convertedString ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...