Three JS - How to scale a moving object

1.5k views Asked by At

I'm trying to scale a moving object in THREE, however when I scale it it will scale my object and move it to another position.

I use the following to set the scale of the object

    // initiates the scale transition
function doTriangleScale(intersection){
  var tween = new TWEEN.Tween(intersection.object.parent.scale)
  .to({
    x: scaleSize,
    y: scaleSize,
    z: scaleSize,
   }, scaleEase)
  tween.start();

  // should have a check if the user is still on the object in question, no time for this now
  setTimeout(function(){
    doTriangleScaleRevert(intersection);
  }, 2000)
}

// triggers the scale revert to default
function doTriangleScaleRevert(intersection) {
  var tween = new TWEEN.Tween(intersection.object.parent.scale)
  .to({
    x: 1, 
    y: 1, 
    z: 1 
  }, scaleEase)
  tween.start();
}

This works if the objects are not moving about, however my objects ARE moving about with the following code in the render animation

scene.traverse(function (e) {
    if (e instanceof THREE.Mesh && e.name != "pyramid") {

        e.rotation.x += rotationSpeed;
        e.rotation.y += rotationSpeed;
        e.rotation.z += rotationSpeed;

        if(triangleFloatLeft){
          e.position.x += 0.01;
        }else{
          e.position.x -= 0.01;
        }
    }
});

I'm looking for a solution that will scale the objects from it's center.

Thanks!

1

There are 1 answers

1
IceCreamYou On BEST ANSWER

Objects scale around their origin. For example, if you have a cube:

var geo = new THREE.BoxGeometry(1, 1, 1);

If you scale a mesh with geometry geo, it will grow around its center. However if you move the geometry's origin:

geo.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0.5, 0));

Now it will grow upwards, because the origin was moved to the box's floor.

The origin of your object is likely not at its center. You can move the origin either in the model itself (if you imported it) or in Three.js as above.