I am using THREE.OrbitControls for rotating my objects. However I would like to add some innertia for camera rotation (if someone stops moving mouse, camera stops after a while). How can I acplish that?
I am using THREE.OrbitControls for rotating my objects. However I would like to add some innertia for camera rotation (if someone stops moving mouse, camera stops after a while). How can I acplish that?
Share Improve this question edited Nov 29, 2013 at 14:59 WestLangley 105k11 gold badges287 silver badges283 bronze badges asked Nov 29, 2013 at 12:30 nmenme 6852 gold badges7 silver badges22 bronze badges 1- 1 Damping / inertia is now a feature of OrbitControls in r.72. See stackoverflow./a/32591676/1461008. – WestLangley Commented Sep 15, 2015 at 17:04
3 Answers
Reset to default 5Here is a very simple way to add inertia in OrbitControls.js:
At the end of the update function (Lines 271-272 currently) you will see the following two variables set to zero:
thetaDelta = 0;
phiDelta = 0;
Change this so that instead of immediately going to zero, they just get smaller over time:
thetaDelta /= 1.5;
phiDelta /= 1.5;
That's it!
For other developers who like me landed here, as of 2019 and three.js r111, the OrbitControls now support inertia out-of-the-box, it's called damping (dont ask me why) but this other answer will show you how to use it.
I used a quick and dirty approach to code in this effect -
In OrbitControls.js
, add this function just inside the main declaration(or anywhere really) -
this.inertiaFunction = function()
{
scope.rotateLeft( ( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed )/dividingFactor);
scope.rotateUp( ( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed )/dividingFactor);
dividingFactor+=0.5;
}
In the onMouseDown(event)
function, add this at the first line -
dividingFactor = 1;
(so that the factor gets reset every time you click)
In the onMouseUp(event)
function, added these lines in the starting -
dragging2=false;
timer = setTimeout(function(){dragging=false;}, 500);
dragging
and dragging2
are two flags that we use in the requestAnimFrame function to determine if the mouse HAS been lifted and 500 milliseconds have NOT passed yet.
Add this in your main animate() or requestAnimationFrame() function -
if(dragging && !dragging2){ controls.inertiaFunction(); }
This checks that if (the mouse has been lifted) AND (500ms haven't passed yet) -
call the inertiaFunction() of the controls object(which is an instance of THREE.OrbitControls
)
For the case that the user clicks within 500ms of lifting the mouse, we use the timer
object to cancel the setTimeOut.
In your onMouseDown function, add this -
if(dragging)
{
clearTimeout(timer);
}
Don't forget to declare dragging
, timer
, and dragging2
and dividingFactor
as global variables. Play with the dividingFactor
and the 500ms in the setTimeout()
to change the distance travelled and duration of the inertial motion.