javascript - 带 for 循环的随机放置问题三.js

标签 javascript for-loop random three.js mesh

我正在尝试创建一个函数来随机化我导入的一些云的位置,但问题是,它生成了云的数量,但在相同的位置!我随机化了位置,但是当代码运行时,我在同一位置有大约 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结构是这样的:enter image description here

我不知道为什么它有这么多的 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)


})

最佳答案

作为 clouds1 获得的 GLTFLoader 结果是一个通用对象,您可以从中正确提取 clouds1.scene。但是,clouds1.scene 也是单个Scene 对象。如果加载的 GLTF 模型中有 10 个云,则 clouds1.scene 将有 10 个子云,您需要像这样循环遍历它们:

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

关于javascript - 带 for 循环的随机放置问题三.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70284292/

相关文章:

javascript - window.close()不是 Electron 函数我在做什么错?

c++ - 数组在 while 循环中未正确初始化

c++ - 在基于范围的 for 循环中使用转发引用有什么好处?

random - 是否可以在 TI-Basic 中制作真正的随机数生成器?

javascript - vuejs 将复选框数组传递给父模板仅传递一个值

javascript - 新的 ECMAScript 5 函数有哪些现代化脚本?

javascript - 如果选中复选框,则添加类,并使用 jquery 将类分配给它的父 div

计算整数阶乘的 JavaScript 函数

c++ - Cplex 随机数 (c++)

c++ - 在 C++ 中生成随机 float 不起作用(Visual Studio 2013)