Paul
Paul

Reputation: 83

Three.js animate from one position to another

Let's say I have a shape at position.x = 0 and I want to smoothly animate it in the render loop to position.x = 2.435. How would I go about that?

Upvotes: 5

Views: 12086

Answers (2)

Pål Thingbø
Pål Thingbø

Reputation: 1301

You can use the THREE AnimationMixer. The function below sets up the animation. Example jsFiddle.

const createMoveAnimation = ({ mesh, startPosition, endPosition }) => {
  mesh.userData.mixer = new AnimationMixer(mesh);
  let track = new VectorKeyframeTrack(
    '.position',
    [0, 1],
    [
      startPosition.x,
      startPosition.y,
      startPosition.z,
      endPosition.x,
      endPosition.y,
      endPosition.z,
    ]
  );
  const animationClip = new AnimationClip(null, 5, [track]);
  const animationAction = mesh.userData.mixer.clipAction(animationClip);
  animationAction.setLoop(LoopOnce);
  animationAction.play();
  mesh.userData.clock = new Clock();
  this.animationsObjects.push(mesh);
};

Upvotes: 9

JJ Gerrish
JJ Gerrish

Reputation: 882

Set your target position as a variable (outside the render loop):

var targetPositionX = 2.435;

Then in your render loop, create an if statement that checks if the object's X position is less than the targetPositionX. If it is , it will add an increment (which you can change based on how fast you want it to move) to the object's X position. When the object's X position becomes greater or equal to the targetPositionX, it will stop moving.

Something like this:

if (object.position.x <= targetPositionX) {
    object.position.x += 0.001; // You decide on the increment, higher value will mean the objects moves faster
}

Here is the full code for the render loop:

function loop(){

    // render the scene
    renderer.render(scene, camera);

    // Check the object's X position
    if (object.position.x <= targetPositionX) {
        object.position.x += 0.001; // You decide on the increment, higher value will mean the objects moves faster
    }

    // call the loop function again
    requestAnimationFrame(loop);
}

Side note

For more detailed/complex animations you may want to look into Tween.js for Three.js which makes animation easier and also allows you to add easing functions to your animation.

You can find it here:

https://github.com/sole/tween.js

I would recommend reading into it if you are getting into Three.js.

Upvotes: 5

Related Questions