我正在尝试创建一个函数来随机化我导入的一些云的位置,但问题是,它生成了云的数量,但在相同的位置!我随机化了位置,但是当代码运行时,我在同一位置有大约 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()
})
我不知道为什么它有这么多的 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/