将对象居中并单击按钮

时间:2019-04-17 10:02:05

标签: three.js

在这里,我试图将对象平移到其他位置时将其置于按钮单击的中心。因此,我尝试通过将刚购买对象的相机位置重置为起始位置来进行尝试,但是我需要在单击任意旋转位置的按钮时将对象置于屏幕中央。 https://jsfiddle.net/Ajay_Venkatesh/thpb8csv/4/

var camera, scene, renderer;
var cube, cube_geometry, cube_material;
var controls;

init();
render();

function init() {

    scene = new THREE.Scene();

    // renderer

    renderer = new THREE.WebGLRenderer({
        alpha: true
    });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // camera

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 12;

    // controls

    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.addEventListener('change', render);
    controls.enableZoom = false;

    // mesh - cube

    cube_geometry = new THREE.CubeGeometry(5, 5, 5);

    for (var i = 0; i < cube_geometry.faces.length; i += 2) {

        var color = Math.random() * 0xffffff;

        cube_geometry.faces[i].color.setHex(color);
        cube_geometry.faces[i + 1].color.setHex(color);
    }

    cube_material = new THREE.MeshLambertMaterial({
        color: 0xffffff,
        vertexColors: THREE.FaceColors
    });

    cube = new THREE.Mesh(cube_geometry, cube_material);
    scene.add(cube);

    // Lights

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

    var light = new THREE.DirectionalLight(0x002288);
    light.position.set(-1, -1, -1);
    scene.add(light);

    var light = new THREE.AmbientLight(0x222222);
    scene.add(light);

    // events

    window.addEventListener('resize', onWindowResize, false);

}

function render() {

    renderer.render(scene, camera);

}

function onWindowResize(event) {

    renderer.setSize(window.innerWidth, window.innerHeight);

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

}

1 个答案:

答案 0 :(得分:0)

也许下面的代码应该做您想要的。单击该按钮时,多维数据集的旋转将发生变化,因此它朝向相机。调用render()很重要,因为您的应用程序中没有动画循环。

button.addEventListener( 'click', ( event ) => {

    cube.lookAt( camera.position );
    render();

} );

演示:https://jsfiddle.net/g91y0ks8/