1

I have a flat surface which I have exploded and tessellated into triangles. I want to get the position of every single face to apply an animation, but apparently I am not able to do that.

if (intersects.length > 0) {

    // if the closest object intersected is not the currently stored intersection object
    if (intersects[0].object != INTERSECTED) {


        if (INTERSECTED) {
            INTERSECTED.face.color.setHex(INTERSECTED.currentHex);
        }

        INTERSECTED = intersects[0];

        INTERSECTED.currentHex = INTERSECTED.face.color.getHex();
        INTERSECTED.face.color.setHex(0xc0392b);
        INTERSECTED.object.geometry.colorsNeedUpdate = true;

        var position = new THREE.Vector3();
        position.setFromMatrixPosition( INTERSECTED.matrixWorld );
        alert(position.x + ',' + position.y + ',' + position.z);
    }
}

I tried to use INTERSECTED.face.matrixWorld.getPosition(), as specified in this example, but it's throwing an error. Here you can find a JSFiddle with the full code. Do you know what's the issue with my code?

Thank in advance for your replies!

Wilt
  • 41,477
  • 12
  • 152
  • 203
d_z90
  • 1,213
  • 2
  • 19
  • 48
  • Have you checked that getPosition is a method on matrixWorld? What kind of error are you getting? – Caleb Jay Mar 15 '16 at 16:45
  • You are right, I have edited the question. I get `Uncaught TypeError: Cannot read property 'elements' of undefined`. Do you have an idea of what is going on? – d_z90 Mar 15 '16 at 16:57
  • I'm not familiar with the library, but I'm not seeing where 'elements' would come from. Is the error coming from code somewhere within the library, particularly the getPosition function? Just off the top of my head that sounds like a `this` is not performing as expected somewhere, and might need some kind of binding. – Caleb Jay Mar 15 '16 at 17:00

1 Answers1

8

A THREE.Face3 has no such thing as a position or a matrix. You need to use the face indexes a, b and c to find the corresponding vertices and then you can calculate your face centroid (also the face gravity point) using those points:

var geometry = INTERSECTED.object.geometry;
var face = INTERSECTED.face;

var vertices = geometry.vertices;
var v1 = vertices[ face.a ];
var v2 = vertices[ face.b ];
var v3 = vertices[ face.c ];

// calculate the centroid
var position = new THREE.Vector3();
position.x = ( v1.x + v2.x + v3.x ) / 3;
position.y = ( v1.y + v2.y + v3.y ) / 3;
position.z = ( v1.z + v2.z + v3.z ) / 3;

Here an updated fiddle.

Wilt
  • 41,477
  • 12
  • 152
  • 203