0

我是一名新开发人员,使用 Three.js 创建 3D 屏幕。我的问题是,我想围绕 3D 对象旋转相机,就像这个网站控制它的相机一样

这个脚本是我在对象周围平滑旋转相机的努力之一。

    <!DOCTYPE html>
<html lang="en">
<head>
    <title>three.js webgl - materials - cube reflection / refraction [Walt]</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>

<body>
<script src="js/libs/three.js-r50/three.js"></script>
<script src="js/libs/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>

<button  onclick="rotateCameraDown();">Down</button>
<button  onclick="rotateCameraUp();">UP</button>
<button  onclick="rotateCameraRight();">Right</button>
<button  onclick="rotateCameraLeft();">Left</button>
<script>
    var  r , phi , theta;
    var camera, scene, renderer;
    var geometry, material, redCube, greenCube;
    init();
    animate();

    function updateAngles(){
        var vec = new THREE.Vector3();
        vec.z =r * Math.sin(theta) * Math.cos(phi) +redCube.position.z;
        vec.x =r * Math.sin(theta) * Math.sin(phi) + redCube.position.x;
        vec.y =r * Math.cos(theta) + redCube.position.y;
        console.log("vec.x "+vec.x+" : "+vec.y+" : "+vec.z+" theta:"+theta+" phi:"+phi);
        return vec;

    }
    function rotateCameraRight(){
        phi +=  Math.PI/40 ;
        camera.position = updateAngles();
        camera.lookAt(redCube.position);
    }
    function rotateCameraLeft(){
        phi -=  Math.PI/40 ;
        camera.position = updateAngles();
        camera.lookAt(redCube.position);
    }
    function rotateCameraDown() {
        theta +=  Math.PI/40 ;
        camera.position = updateAngles();
        camera.lookAt(redCube.position);
    };
    function rotateCameraUp() {

        theta -=  Math.PI/40 ;
        camera.position = updateAngles();
        camera.lookAt(redCube.position);

    };

    function init() {
        r = 5;
        phi = 0;
        theta = Math.PI/4;
        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);

        scene = new THREE.Scene();

        renderer = new THREE.CanvasRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);

        document.body.appendChild(renderer.domElement);

        geometry = new THREE.CubeGeometry(2, 2, 2);
        material = new THREE.MeshBasicMaterial({ color:0xff0000,wireframe:true });
        redCube = new THREE.Mesh(geometry, material);
        redCube.position.z = 5;
        redCube.position.y = 5;
        redCube.position.x = 5;
        camera.lookAt(redCube.position);
        scene.add(redCube);
        scene.add(camera);


    }



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

</script>
</body>
</html>
4

0 回答 0