2

After loading a .obj model in Three.js I am unable to find vertices data. Vertices data is needed to apply collision detection as suggested by this answer

var loader = new THREE.OBJLoader();
loader.load('models/wall.obj', function ( object ) {
    object.traverse( function ( node ) {
       if ( node.isMesh ) {
         console.log(node);
       }
    }); 
    scene.add( object );                
});

In mesh there is geometry.attributes.position.array but I am unable to find "vertices" anywhere in object.

Right now trying to convert position.array data to vertices but below code is not working, this answer is pointing the problem correctly but I am unable to use it to solve the issue:

var tempVertex = new THREE.Vector3();
// set tempVertex based on information from mesh.geometry.attributes.position
mesh.localToWorld(tempVertex);
// tempVertex is converted from local coordinates into world coordinates,
// which is its "after mesh transformation" position
gman
  • 100,619
  • 31
  • 269
  • 393
XIMRX
  • 2,130
  • 3
  • 29
  • 60
  • Can you please share your code that shows how you fill `tempVertex` with the `position` attribute data? – Mugen87 Jan 28 '20 at 15:06

1 Answers1

4

geometry.attributes.position.array IS the vertices. Every three values makes up one vertex. You will also want to look at the index property (geometry.index), because that is a list of indices into the position array, defining the vertices that make up a shape. In the case of a Mesh defined as individual triangles, every three indices makes up one triangle. (Tri-strip data is slightly different, but the concept of referencing vertex values by the index is the same.)

You could alternately use the attribute convenience functions:

These functions take the index into account. So if you want the first vertex of the first triangle (index = 0):

let pos = geometry.attributes.position;
let vertex = new THREE.Vector3( pos.getX(0), pos.getY(0), pos.getZ(0) );

This is equivalent to:

let pos = geometry.attributes.position.array;
let idx = geometry.index.array;
let size = geometry.attributes.position.itemSize;

let vertex = new THREE.Vector3( pos[(idx[0] * size) + 0], pos[(idx[0] * size) + 1], pos[(idx[0] * size) + 2] );

Once you have your vertex, then you can use mesh.localToWorld to convert the point to world-space.

TheJim01
  • 8,411
  • 1
  • 30
  • 54
  • 1
    `let pos = geometry.attributes.position; let vertex = new THREE.Vector3().fromBufferAttribute(pos, 0);` will do the same thing, but in more convenient way. [reference](https://threejs.org/docs/index.html#api/en/math/Vector3.fromBufferAttribute) – prisoner849 Jan 28 '20 at 21:09
  • 1
    @prisoner849 I guess I learned about yet another new convenience function today. :) – TheJim01 Jan 29 '20 at 14:10