Inertia in OrbitControls from ThreeJS

心不动则不痛 提交于 2020-01-11 06:32:11

问题


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 accomplish that?


回答1:


Here 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!




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/20285892/inertia-in-orbitcontrols-from-threejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!