three.js - zoom in/out complete tube geometry

一笑奈何 提交于 2019-12-06 05:12:41
foxdanni
document.body.addEventListener( 'mousewheel', mousewheel, false );
document.body.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox


function mousewheel( e ) {      
    var d = ((typeof e.wheelDelta != "undefined")?(-e.wheelDelta):e.detail);
    d = 100 * ((d>0)?1:-1);

    var cPos = camera.position;
    if (isNaN(cPos.x) || isNaN(cPos.y) || isNaN(cPos.y))
      return;

    var r = cPos.x*cPos.x + cPos.y*cPos.y;
    var sqr = Math.sqrt(r);
    var sqrZ = Math.sqrt(cPos.z*cPos.z + r);


    var nx = cPos.x + ((r==0)?0:(d * cPos.x/sqr));
    var ny = cPos.y + ((r==0)?0:(d * cPos.y/sqr));
    var nz = cPos.z + ((sqrZ==0)?0:(d * cPos.z/sqrZ));

    if (isNaN(nx) || isNaN(ny) || isNaN(nz))
      return;

    cPos.x = nx;
    cPos.y = ny;
    cPos.z = nz;
}

or even simpler ajusting only the camera :

var mousewheel  = function ( e ) {
     var d = ((typeof e.wheelDelta != "undefined")?(-e.wheelDelta):e.detail);
     d = 100 * ((d>0)?1:-1);    
     var cPos = camera.position;
     if (isNaN(cPos.x) || isNaN(cPos.y) || isNaN(cPos.y)) return;

        // Your zomm limitation
        // For X axe you can add anothers limits for Y / Z axes
        if (cPos.x > _YOUR_ZOOM_MIN_X_ || cPos.x < _YOUR_ZOOM_MAX_X_ ){
           return ;
        }

   mb = d>0 ? 1.1 : 0.9;
   cPos.x = cPos.x * mb;
   cPos.y = cPos.y * mb;
   cPos.z = cPos.z * mb;
}

As with any conventional real life camera, you can change the focal length (zoom) of THREE.PerspectiveCamera by calling setLens method. I find this way very intuitive and much simplier than moving the camera to zoom in/out.

Here is the method docs in three.js:

/**
 * Uses Focal Length (in mm) to estimate and set FOV
 * 35mm (fullframe) camera is used if frame size is not specified;
 * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
 */
THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight )
...

And here is an example usage:

var focalLength = 25.734; // equivalent to FOV=50
$('#scene').mousewheel(function (event, delta, deltaX, deltaY) {
    event.preventDefault();

    focalLength += deltaY;
    camera.setLens(focalLength);
});

The method jQuery.fn.mousewheel is provided by Mousewheel Plugin.

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