Changing from THREE.Geometry to THREE.BufferGeometry with THREE JS

542 views Asked by At

Hi I'm new to Three JS and need a little help. I am using a piece of code I found to create a sphere of random points but since THREE.Geometry has since been depreciated I need to change THREE.Geometry to THREE.BufferGeometry in the code.

The original code is :

var pointsGeometry = new THREE.Geometry();

for (var i = 0; i < 1000; i++) {


    var vector = new THREE.Vector3();
     
    // for simplicity I have omitted script 
    // that would be placed here for creating random 
    // values for vector.x, vector.y, vector.z etc etc

    pointsGeometry.vertices.push(vector);

}

So now I believe I need to use:

const pointsGeometry = new THREE.BufferGeometry();

but how do I push each vector into an array that exists in an attribute of pointsGeometry named 'vertices'?

In the for loop I cannot use :

pointsGeometry.setAttribute( 'vertices', new THREE.Float32BufferAttribute( vector ) );

I thought I needed to manually create an array 'vectorsArray' and push each vector into the array in the for loop and then add it after the loop

pointsGeometry.setAttribute( 'vertices', new THREE.Float32BufferAttribute( vectorsArray ) );

while this does create a vertices attribute and add an array of 1000, each value is NaN when it should be:

0: Object { x: -21.16441539757467, y: 112.77250047881454, z: -37.63426937227097, … } etc

I have checked that vectorsArray does posses the correct values which they do, but for some reason they are not getting passed into pointsGeometry.setAttribute( 'vertices'). What am I doing wrong please?

Thanks in advance.

1

There are 1 answers

4
Mugen87 On

Try it like so:

const geometry = new THREE.BufferGeometry();

const points = [];
const point = new THREE.Vector3();

for ( let i = 0; i < 1000; i ++ ) {

    point.random();
    points.push( point.x, point.y, point.z );

}

geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( points, 3 ) );

When using this geometry with THREE.Points, it will create a random point cloud.