Search code examples
three.jsrotationpositionvertices

How to get the exact x,y,z location of all the corners of a cube in three.js


There's another answer to this question, but after implementing it, I saw the positions were not true representations of the absolute x,y,z locations of the vertices. I examined the mesh, and looked at the _corners array in the geometry:BoxGeometry property. There I can also find the values. If the cube is rotating on two different axis, and moving on the x and z axis, the y value of the corner position does not change, so these are not accurate values of the x, y and z positions of the corners. I can visibly see the corner positions are moving on the x, y and z axis.

How else can I derive accurate, absolute positions of these corners? So far I cannot find the properties to determine this. Will I need to apply some kind of math using the rotation values with these corner positions?


Solution

  • You only need to get the WorldMatrix of your cube (which contains all transformations) and apply it to a Vector3 with the original vertex positions:

    var w = 10;
    var h = 15;
    var d = 7;
    
    const geom = new THREE.BoxBufferGeometry(w, h, d);
    const mat = new THREE.MeshBasicMaterial();
    const box = new THREE.Mesh(geom, mat);
    
    // Get world matrix transformation of the box
    var boxMatrix = box.matrixWorld;
    
    // Set the initial position of the desired vertex into a Vector3
    var vertex = new THREE.Vector3(w / 2, h / 2, d / 2);
    
    // Apply the matrix transformation to the vector
    vertex.applyMatrix4(boxMatrix);
    
    // Read the result
    console.log(vertex);