user2194221
user2194221

Reputation: 121

Three.js move and rotate the center of geometry

I have a complex model loaded with OBJLoader. I want to move and rotate its center to let the user ( the user of my application ) to place the center point where he/she wants. I'm aware of this: old question, but for me does not work. This is a test in fiddle : fiddle example

Pressing the button in the example I expect that the center is moved. The code in the button is :

objMesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(new THREE.Vector3(1, 0.1, 0.1)));

Upvotes: 1

Views: 10194

Answers (2)

WestLangley
WestLangley

Reputation: 104843

Use

mesh.geometry.translate( x, y, z );

or

mesh.geometry.center();

Also, consider just calling mesh.position.set(), rather than moving each vertex of the geometry.

three.js r.95

Upvotes: 2

user2194221
user2194221

Reputation: 121

I found the solution empirically, but I don't understand why it works. I post the code to help and maybe someone could explain me what I found.

The code below shift the center in x for 0.1 units.

var x = 0.1;
var y = 0;
var z = 0;

for (var i = 0; i < object.children.length; i++)
{
    var geometry = object.children[i].geometry;

    object.children[i].centroid.divideScalar(geometry.vertices.length); // Why this line ?

    var offset = object.children[i].centroid.clone(); 
    object.children[i].geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x+x, -offset.y+y, -offset.z+z));
    object.children[i].position.x -= x;
    object.children[i].position.y -= y;
    object.children[i].position.z -= z;
    object.children[i].geometry.verticesNeedUpdate = true;
}

Upvotes: 3

Related Questions