2016-11-08 61 views
0

所以我的問題是,我試圖在three.js內創建一個隨機星圖,當縮小成爲一個由星星創建的行星(球體)。隨機立方體在三個js中隨機球體

目前使用的代碼隨機生成我的星星,但當我縮小它是一個立方體,而不是球體。

for (var i = 0;i<2000;i++){ 
       var mesh = new THREE.Mesh(geometry, material); 
       mesh.position.x = (Math.random() - 0.5) * 4000 * Math.random(); 
       mesh.position.y = (Math.random() - 0.5) * 4000* Math.random() ; 
       mesh.position.z = (Math.random() - 0.5) * 4000* Math.random() ; 

       mesh.rotation.x = Math.random(); 
       mesh.rotation.y = Math.random(); 
       mesh.rotation.z = Math.random(); 

       scene.add(mesh); 
       objects.push(mesh); 
      } 

這是for循環中,我產卵我的明星和線3-6是什麼決定然而明星產卵的方式,所有我已經能夠做的是數學隨機創建再乘以定位略少定義的立方體而不是我想要的球體。

回答

0

而不是設置網格的x,y,z位置像你一樣,嘗試這樣

var newPos = new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize().multiplyScalar(4000 * Math.random()); 
mesh.position.copy(newPos); 

因此您設置一個隨機向量,那麼你就歸它,使得它的長度等於1,然後用隨機乘以值。簡而言之:你設定方向和距離。

有一個jsfiddle例如用兩種溶液(礦和加法器的)

1

僅有修剪球體外部的分:

var R=2000; 
for (var i = 0;i<2000;){ 
    var mesh = new THREE.Mesh(geometry, material); 
    mesh.position.x = (Math.random() - 0.5) * R*2 * Math.random(); 
    mesh.position.y = (Math.random() - 0.5) * R*2 * Math.random() ; 
    mesh.position.z = (Math.random() - 0.5) * R*2 * Math.random() ; 

    mesh.rotation.x = Math.random(); 
    mesh.rotation.y = Math.random(); 
    mesh.rotation.z = Math.random(); 

    var distance_squared = mesh.position.x*mesh.position.x + mesh.position.y*mesh.position.y + mesh.position.z*mesh.position.z; 

    if(distance_squared <= R*R) { 
     scene.add(mesh); 
     objects.push(mesh); 
     ++i; 
    } 
} 
+0

似乎'如果(mesh.position.length()<= R)'也可以工作 – prisoner849

+0

是的,不知道 - 但它使用的平方根操作有點慢。 – Adder

+0

我不堅持)也有可能是'mesh.position.lengthSq()<= R * R' – prisoner849