KAI ATTEWELL KAI ATTEWELL - 25 days ago 19
Javascript Question

Turning random cube to random sphere in three js

So my issue is that i am trying to create a random star chart within three.js that when zoomed out becomes a planet(sphere) created from the stars.

Currently the code im using randomly generates my stars yet when i zoom out it is a cube, not a sphere.

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


This is the for loop in which i spawn my stars and line 3-6 are what determines the way the stars spawn however all i have been able to do is multiply the positioning again by math random to create a slightly less defined cube instead of my desired sphere.

Answer

Just prune the stars outside a sphere:

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;
    }
}
Comments