KAI ATTEWELL
KAI ATTEWELL

Reputation: 33

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.

Upvotes: 0

Views: 921

Answers (2)

prisoner849
prisoner849

Reputation: 17586

Instead of setting mesh's x,y,z position like you do, try it this way

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

Thus you set a random vector, then you normalize it, making its length equal to 1, then multiply it with a random value. In simple words: you set direction and distance.

There's a jsfiddle example with both solutions (mine and Adder's)

Upvotes: 0

Adder
Adder

Reputation: 5868

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

Upvotes: 1

Related Questions