create_deploy
create_deploy

Reputation: 23

adding and updating velocity and acceleration in bufergeometry three js

let pointsM = [];

  let img = new THREE.TextureLoader().load( 'image' );
  let pointMaterial = new THREE.PointsMaterial({
  map: img,transparent:true
  });
  let bufferGeometry = new THREE.BufferGeometry()
  for (let i = 0; i < 10; i++) {
    pointsM.push( new THREE.Vector3(Math.random() * 20 - 10, Math.random() * 20 - 10, Math.random() * 20 - 10));
  }
  bufferGeometry.setFromPoints(pointsM);
  bufferGeometry.computeVertexNormals();

  pointsmesh = new THREE.Points(bufferGeometry, pointMaterial);
  scene.add(pointsmesh)

The above section works fine , converted from Geometry to BufferGeometry

What id like to do is add velocity and acceleration to the points created in the above section, and update them in the render loop

i would like to change the code below to work with buffer geometry currently it works with Geometry

  render(){

  Geo.vertices.forEach(p => {
   p.vel += p.accel; 
   p.z -= p.vel;

  });
  Geo.verticesNeedUpdate = true;
}

Thanks for the support

Upvotes: 2

Views: 876

Answers (1)

Mugen87
Mugen87

Reputation: 31036

Try it with the below code. It assumes that the velocity and acceleration for each vertex is saved in two separate arrays.

// creation

const bufferGeometry = new THREE.BufferGeometry();
const vertices = [];
const velocities = [];
const accelerations = [];

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

    vertices.push( Math.random() * 20 - 10 ); // x
    vertices.push( Math.random() * 20 - 10 ); // y
    vertices.push( Math.random() * 20 - 10 ); // z

    velocities.push( 0 );
    accelerations.push( Math.random() );

}

bufferGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );

// update

const positionAttribute = geometry.getAttribute( 'position' );

for ( let i = 0; i < positionAttribute.count; i ++ ) {

    const z = positionAttribute.getZ( i );  

    const vel = velocities[ i ];
    const accel = accelerations[ i ];
    vel *= accel;
    velocities[ i ] = vel;
    z -= vel;

    positionAttribute.setZ( i, z );

}

positionAttribute.needsUpdate = true;

render();

BTW: computeVertexNormals() is not necessary in your use case. Points and lines to not need vertex normals.

Upvotes: 2

Related Questions