for-loop 的随机放置问题 three.js

random plancement issue three.js with for-loop

我正在尝试创建一个函数来随机化我导入的一些云的位置,但问题是,它生成了云的数量,但位置相同!我将位置随机化,但当代码运行时,我在同一位置有 10 朵云。我能做什么?这是代码:

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()
  
})

编辑:clouds1.scene结构是这样的:

不知道为什么有这么多children,我试着用答案解决了,还是不行。最后的第 3 个 child 包含网格,我尝试使用它来工作,但它说我不能在 scene.add() 函数

中使用它

编辑:我解决了问题!我只需要将 for 循环放在加载函数之外

 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)


})

GLTFLoader 结果,因为 clouds1 是通用的 object,您可以从中正确提取 clouds1.scene。然而,clouds1.scene也是一个单一的Sceneobject。如果您加载的 GLTF 模型中有 10 个云,那么 clouds1.scene 将有 10 个 children,您需要像这样循环遍历它们:

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)
  
  }
  
})