0

When i use the "w" key to move my object and then pres the "x" key to rotate it, my object rotates around the world origin rather than its own center. How do I update the objects pivot after the move? I've seen a few questions and answers on this where its stated to use geometry.center(), however, this doesn't work for me.

var tMatrix = new THREE.Matrix4()
var radian = 5*Math.PI/180
function keyDown(event){

    if(event.key == 'x'){
        r5 = Math.cos(radian);
        r6 = -Math.sin(radian);
        r8 = Math.sin(radian);
        r9 = Math.cos(radian);
        tMatrix.set( 1, 0, 0, 0,
                    0, r5, r6, 0,
                    0, r8, r9, 0,
                    0, 0, 0, 1 );
        mesh.applyMatrix4(tMatrix);

    }

    if(event.key == 'w'){
        tMatrix.set( 1, 0, 0, 0,
                    0, 1, 0, 1,
                    0, 0, 1, 0,
                    0, 0, 0, 1 );
        mesh.applyMatrix4(tMatrix);

    }
}


var pivot = new THREE.Object3D();
let loader = new THREE.STLLoader();
var material = new THREE.MeshLambertMaterial({color: 0x818181});

loader.load('STL/test.stl', function (geometry) {
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);
});

window.addEventListener("keypress", keyDown);
Forrest
  • 157
  • 14
  • Is it a requisite to manually assign individual elements to a `Matrix4`? You could easily achieve this by using `mesh.position.x = ??;` and `mesh.rotation.y = ??;` and Three.js would take care of all matrix calculations for you. It would maintain the pivot around the center of the geometry, even after a translation. – M - Feb 27 '20 at 21:24
  • This won't work for what I am trying to do. I need to update Pivot – Forrest Feb 27 '20 at 21:59
  • Have you seen [this answer](https://stackoverflow.com/questions/50255183/threejs-how-to-change-the-rotation-center-of-a-object)? Or [this one](https://stackoverflow.com/questions/11911065/three-js-move-geometrys-center)? – M - Feb 27 '20 at 22:03

1 Answers1

0

Okay, I solved the problem by just getting the position of the object before I rotate it, and then set the position to its original after the new matrix has been set.

if(event.key == 'x'){
    x = mesh.position.x;
    y = mesh.position.y;
    z = mesh.position.z;

    r5 = Math.cos(radian);
    r6 = -Math.sin(radian);
    r8 = Math.sin(radian);
    r9 = Math.cos(radian);
    tMatrix.set( 1, 0, 0, 0,
                0, r5, r6, 0,
                0, r8, r9, 0,
                0, 0, 0, 1 );
    mesh.applyMatrix4(tMatrix);
    mesh.position.set(x,y,z);
}
Forrest
  • 157
  • 14