ThreeJS全场景最小旋转

时间:2018-09-27 05:30:46

标签: three.js

我想知道当您将鼠标移到该网站(http://www.cryptarismission.com/)上时如何面对不同的方向。

在他们的主页上,似乎当您移动鼠标时,场景会在很少的轴旋转中平稳地跟随。

使用Three.js,这件事背后的想法是什么?我知道您可以旋转对象,场景或相机,但不确定旋转什么。我正在考虑旋转整个场景容器,但我不知道这是否很好。

1 个答案:

答案 0 :(得分:0)

您可以根据鼠标位置在每个循环中更改相机位置并调用lookAt,也可以更改整个场景旋转。这是第一种方法的工作原理。

<!DOCTYPE html>
<html lang="en">

<head>
    <title>ThreeJS full scene minimal rotation</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
    <style>
        body {
            margin: 0px;
            padding: 0px;
            overflow: hidden;
        }
    </style>
</head>

<body>
    <canvas></canvas>
</body>

<script>
    var camera, scene, renderer, stats, windowHalfX = window.innerWidth / 2,
        windowHalfY = window.innerHeight / 2,
        mouseX = 0,
        mouseY = 0;

    init();
    animate();

    function init() {
        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
        camera.position.set(30, 30, 30)
        scene = new THREE.Scene();

        scene.add(new THREE.Mesh(
            new THREE.BoxGeometry(5, 5, 5),
            new THREE.MeshBasicMaterial({ color: 0x00ff00 })
        ));

        renderer = new THREE.WebGLRenderer({ antialias: true, canvas: document.querySelector('canvas') });
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        window.addEventListener('mousemove', onDocumentMouseMove, false);
    }

    function onDocumentMouseMove(event) {
        mouseX = (event.clientX - windowHalfX) / 10;
        mouseY = (event.clientY - windowHalfY) / 10;
    }

    function animate() {
        requestAnimationFrame(animate);
        render();
    }

    function render() {
        camera.position.x += (mouseX - camera.position.x) * .05;
        camera.position.y += (-mouseY - camera.position.y) * .05;
        camera.lookAt(scene.position);
        renderer.render(scene, camera);
    }
</script>

</html>