如何以编程方式将三个js中的网格聚焦在单击按钮上?

时间:2019-11-05 05:55:53

标签: javascript three.js

单击按钮后,我有三个js网格,网格需要基于按钮进行聚焦 例如,在单击视图时,顶部摄像头需要从网格顶部聚焦
在three.js中,是否有任何内置方法可以聚焦网格或如何计算网格的左上角?

var scene, camera, renderer, controls;
var ROTATE = true;

function init() {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(45, 450 / 450, 0.1, 1000);
    renderer = new THREE.WebGLRenderer();
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.userPan = false;
    controls.userPanSpeed = 0.0;
    controls.maxDistance = 5000.0;
    controls.maxPolarAngle = Math.PI * 0.495;
  //  controls.rotateUp(Math.PI * 0.1);
   // controls.autoRotate = ROTATE; //true:自動回転する,false:自動回転しない
    controls.autoRotateSpeed = 4.0; //自動回転する時の速度

    renderer.setSize(465, 465);
    renderer.shadowMapEnabled = true;
    camera.position.x = 0;
    camera.position.y = 0;
    camera.position.z = 150;
    camera.lookAt(scene.position);

    var spotLight = new THREE.SpotLight(0xffffff);
    spotLight.position.set(100, 100, -100);
    scene.add(spotLight);

    var light = new THREE.DirectionalLight(0xffffff, 1.5);
    light.position.set(100, 100, 100).normalize();
    scene.add(light);

    var light2 = new THREE.DirectionalLight(0xffffff);
    light2.position.set(-100, -100, -100).normalize();
    scene.add(light2);

    document.body.appendChild(renderer.domElement);
    var parser = new vox.Parser();
    // yuusha.vox
    parser.parse("https://rawcdn.githack.com/siouxcitizen/3DModel/b2d06e45f6b64c3e342b724a4ec5a0c427a4ce0a/vox/hiyoko.vox").then(function(voxelData) {
        var builder = new vox.MeshBuilder(voxelData, {
            voxelSize: 7.0,
            vertexColor: true,
            optimizeFaces: false,
        });
        var v0 = builder.createMesh();
        v0.position.y -= 50;
        scene.add(v0);
    });
    render();
}

function render() {
    controls.update();
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}

init();
function topView(){
  alert("topView view") 
}

function sideView(){
  alert("sideview view") 
}

function frontiew(){
  alert("front view") 
}
* {
  margin: 0;
  padding: 0;
  border: 0;
  overflow: hidden;
}

body {
  background: #000;
  font: 30px sans-serif;
}
button{
  padding:5px 10px
}
<!-- three.min.js r87 -->

<button onClick={topView()}>top view</button>
<button onClick={frontiew()}>front view</button>
<button onClick={sideView()}>side view</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>

<!-- vox.js v1.0.1 -->
<script src="https://cdn.jsdelivr.net/gh/daishihmr/vox.js@1.0.1/build/vox.min.js"></script>

<!-- Old OrbitControls.js -->
<script src="https://codepen.io/siouxcitizen/pen/XWWXZZN.js"></script>

上面是演示代码。 我尝试强制更新相机位置,这将不起作用

1 个答案:

答案 0 :(得分:1)

您可以使用新的THREE.Box3()。setFromObject(mesh)获得轴对齐的bbox 接下来-将相机安装到此框中。 这是我要做的代码(打字稿)(与PerspetiveCamera和OrbitControls配合使用)。

expand