Tween camera position while rotation with slerp -- THREE.js
Asked Answered
E

1

11

I want to tween camera position while rotation.

Here is my function:

function moveAndLookAt(camera, dstpos, dstlookat, options) {
  options || (options = {duration: 300});

  var origpos = new THREE.Vector3().copy(camera.position); // original position
  var origrot = new THREE.Euler().copy(camera.rotation); // original rotation

  camera.position.set(dstpos.x, dstpos.y, dstpos.z);
  camera.lookAt(dstlookat);
  var dstrot = new THREE.Euler().copy(camera.rotation)

  // reset original position and rotation
  camera.position.set(origpos.x, origpos.y, origpos.z);
  camera.rotation.set(origrot.x, origrot.y, origrot.z);

  //
  // Tweening
  //

  // position
  new TWEEN.Tween(camera.position).to({
    x: dstpos.x,
    y: dstpos.y,
    z: dstpos.z
  }, options.duration).start();;

  // rotation (using slerp)
  (function () {
    var qa = camera.quaternion; // src quaternion
    var qb = new THREE.Quaternion().setFromEuler(dstrot); // dst quaternion
    var qm = new THREE.Quaternion();

    var o = {t: 0};
    new TWEEN.Tween(o).to({t: 1}, options.duration).onUpdate(function () {
      THREE.Quaternion.slerp(qa, qb, qm, o.t);
      camera.quaternion.set(qm.x, qm.y, qm.z, qm.w);
    }).start();
  }).call(this);
}

It works great: http://codepen.io/abernier/pen/zxzObm


The only problem is the tween for rotation does NOT seem to be linear... causing decay with position's tween (which is linear).

How can I turn slerp into a linear tween ?

Thank you

Eterne answered 22/1, 2015 at 14:59 Comment(3)
I thought slerp keeps a constant velocity, but it appears that not...Eterne
number-none.com/product/… slerp should keep a constant velocity, nlerp does notQualls
@BrendanAnnable what I don't understand is : if slerp is supposed to keep constant velocity (ie: linear) and my position tween is linear (no easing), why this decay ?Eterne
P
13

In your code

// rotation (using slerp)
(function () {
var qa = camera.quaternion; // src quaternion

Change it to

qa = new THREE.Quaternion().copy(camera.quaternion); // src quaternion

The way you do it, qa is the same as the camera quaternion, and it feeds back in the slerp calculus. It must be a constant variable.

Parra answered 26/1, 2015 at 19:54 Comment(1)
Excellent!! It works great: codepen.io/abernier/pen/LEjPBX, thank you! Have this bounty :)Eterne

© 2022 - 2024 — McMap. All rights reserved.