ilovetoast
ilovetoast

Reputation: 65

Threejs OrbitControls and Tween

I have been searching the internet to figure out how I can add a tween to orbitControls on threejs.

Actual Goals:

  1. Rotate a camera around an object based on mouse movement.
  2. Tween the movement for a smooth camera easing

I can achieve #2 by just moving the camera position in the animation loop, but I'm not familiar with the math to move the camera around the object while angling it back at a center point (orbiting). This solved #2, but not #1

On the other man orbitControls accomplishes #1, but I'm not sure how to interact with the controls to add a tween on its update.

Thanks! Michael

Upvotes: 2

Views: 1703

Answers (1)

andrevenancio
andrevenancio

Reputation: 554

You can rotate any object around a point simply by using sine and cosine. You choose a targetPosition (or target object) and you update the camera.position and the lookAt method at runtime. The reason I added z instead of y is because I'm assuming you want to rotate it in depth and not vertically. Inside the Math.cos and Math.sin there's a time reference, and you can play around with that to change the speed of the rotation.

var targetPosition = new THREE.Vector2(100, 100);
var radius = 50;

function update() {
    requestAnimationFrame(update);
    camera.position.x = targetPosition.x + Math.cos(Date.now()/1000) * radius;
    camera.position.z = targetPosition.y + Math.sin(Date.now()/1000) * radius;
    camera.lookAt(targetPosition);
}

If you just wan't to do a tween from position A to position B, when the user clicks a button (for example) you should create a target THREE.Vector3 and just tween that vector to the desired position, and on the update() just add

var cameraPosition = new THREE.Vector3();

window.addEventListener('click', handleClick, false);

function handleClick(e) {
    TweenMax.to(cameraPosition, 1, { x: 100, y: 100, z: 100 });
}

function update() {
    requestAnimationFrame(update);
    camera.position.copy(cameraPosition);
}

Upvotes: 1

Related Questions