在 THREE.JS 中设置与两个网格的最小距离
Posted
技术标签:
【中文标题】在 THREE.JS 中设置与两个网格的最小距离【英文标题】:set minimum distance from two meshes in THREE.JS 【发布时间】:2022-01-14 18:44:46 【问题描述】:我有这段代码可以生成一些随机位置、旋转和随机比例的云。由于它们可以在另一个网格旁边或另一个网格旁边生成,因此它们可以夹在一起。我想设置一个最小距离,比如if(cloud position x and z is < 10 FROM ANOTHER CLOUD) then set distance
我该怎么办?代码如下:
for(let i = 0; i < 10; i+= 1)
loader.load('/clouds/clouds2/scene.gltf', function (clouds2)
const cloud = clouds2.scene
const child1 = cloud.children[0].children[0].children[0].children[2].children[0]
const child2 = cloud.children[0].children[0].children[0].children[3].children[0]
const child3 = cloud.children[0].children[0].children[0].children[4].children[0]
child1.material = new THREE.MeshStandardMaterial( emissive: 'white', emissiveIntensity: 0.3)
child2.material = new THREE.MeshStandardMaterial( emissive: 'white', emissiveIntensity: 0.3)
child3.material = new THREE.MeshStandardMaterial( emissive: 'white', emissiveIntensity: 0.3)
cloud.scale.x = (Math.random() * (0.06 - 0.04 ) + 0.04)
cloud.scale.y = (Math.random() * (0.06 - 0.04 ) + 0.04)
cloud.scale.z = (Math.random() * (0.06 - 0.04 ) + 0.04)
cloud.position.x = (Math.random() - 0.5) * 500
cloud.position.y = (Math.random() + 80)
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)
)
【问题讨论】:
【参考方案1】:首先,静态放置事物,然后使用随机值来创建差异并不可耻。例如,考虑一组排列在正方形角落的 4 朵云。如果您随后使用固定范围的随机值修改它们的位置,您将获得随机效果,同时仍保持分离。
const clouds = [...] // cloud meshes
const maxChange = ... // the maximum amount of position change in one direction
const staticPositions = [
new THREE.Vector3(...),
new THREE.Vector3(...),
new THREE.Vector3(...),
new THREE.Vector3(...)
]
for(let i = 0; i < 4; ++i)
let cloud = clouds[i]
cloud.position.copy(staticPositions[i])
// random variance
cloud.position.x += (Math.random() * (maxChange * 2)) - maxChange
cloud.position.y += (Math.random() * (maxChange * 2)) - maxChange
cloud.position.z += (Math.random() * (maxChange * 2)) - maxChange
但如果你真的想完全随机,那么你需要在提交之前对照所有其他云检查新位置。
const clouds = [...] // cloud meshes
const minDistanceSquared = ... // the minimum (squared) distance allowed between clouds
// checks if a cloud is far enough away from all other clouds
function isFarEnoughAway(cloud)
let retVal = true
for(let i = 0, l = clouds.length; i < l && retVal; ++i)
if(cloud !== clouds[i] && cloud.position.distanceToSquared(clouds[i].position) < minDistSquared)
retVal = false
return retVal
【讨论】:
以上是关于在 THREE.JS 中设置与两个网格的最小距离的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 three.js r71 合并两个几何图形或网格?