Home > Web Front-end > JS Tutorial > Three.js uses object composition instance methods

Three.js uses object composition instance methods

小云云
Release: 2018-03-14 17:32:22
Original
2974 people have browsed it

Putting multiple models into a group is an object combination. Creating groups is very simple, each grid you create can contain child elements, and child elements can be added using the add function. The effect of adding child elements to a group is that you can move, scale, rotate and transform the parent object, and all child objects will be affected.

Implementation of object combination

Object combination is easy to implement. First create an object of the class THREE.Object3D. This is the base class for THREE.Mesh and THREE.Scene, but it contains nothing of its own and does not render anything. Please note that a new object named THREE.Group was introduced in the latest version of THREE.js to support grouping. This object is identical to the THREE.Object3D object, and the two are interchangeable.

    var group = new THREE.Object3D(); //实例化一个THREE.Object3D对象
    group.add(sphere); //在对象里面添加第一个子元素
    group.add(cube); //在对象里面添加第二个子元素
    scene.add(group); //将对象组添加到场景当中
Copy after login

The code is as above, we have implemented a scene group.

Note: When you rotate a group, you do not rotate each object in the group individually, but rather rotate the entire group around its center (in our case, around group The center of the object rotates the entire group).

When using groups, you can still reference, modify and position each individual geometry. The only thing to remember is that all positioning, rotation and transformation are relative to the parent object.

Case code

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        html, body {            margin: 0;            height: 100%;        }

        canvas {            display: block;        }

    </style></head><body onload="draw();"></body><script src="/lib/three.js"></script><script src="/lib/js/controls/OrbitControls.js"></script><script src="/lib/js/libs/stats.min.js"></script><script src="/lib/js/libs/dat.gui.min.js"></script><script>
    var renderer;    function initRender() {
        renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setSize(window.innerWidth, window.innerHeight);        //告诉渲染器需要阴影效果
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是,没有设置的这个清晰 THREE.PCFShadowMap
        document.body.appendChild(renderer.domElement);
    }    var camera;    function initCamera() {
        camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
        camera.position.set(0, 40, 50);
        camera.lookAt(new THREE.Vector3(0,0,0));
    }    var scene;    function initScene() {
        scene = new THREE.Scene();
    }    //初始化dat.GUI简化试验流程
    var gui;    function initGui() {
        //声明一个保存需求修改的相关数据的对象
        gui = {
            sphereX:-5, //球的x轴的位置
            sphereY:5, //球的y轴的位置
            sphereZ:0, //球的z轴的位置
            sphereScale:1, //球的缩放

            cubeX:15, //立方体的x轴位置
            cubeY:5, //立方体的y轴位置
            cubeZ:-5, //立方体的z轴的位置
            cubeScale:1, //立方体的缩放

            groupX:0, //模型组的x轴位置
            groupY:0, //模型组的y轴位置
            groupZ:0, //模型组的z轴的位置
            groupScale:1, //模型组的缩放

            grouping:false, //是否整个模型组旋转
            rotate:false, //是否旋转
        };        var datGui = new dat.GUI();        //将设置属性添加到gui当中,gui.add(对象,属性,最小值,最大值)

        //球型的操作
        var sphereFolder = datGui.addFolder("sphere");
        sphereFolder.add(gui,"sphereX",-30,30).onChange(function (e) {
            sphere.position.x = e;
        });
        sphereFolder.add(gui,"sphereY",-30,30).onChange(function (e) {
            sphere.position.y = e;
        });
        sphereFolder.add(gui,"sphereZ",-30,30).onChange(function (e) {
            sphere.position.z = e;
        });
        sphereFolder.add(gui,"sphereScale",0,3).onChange(function (e) {
            sphere.scale.set(e, e, e);
        });        //立方体的操作
        var cubeFolder = datGui.addFolder("cube");
        cubeFolder.add(gui,"cubeX",-30,30).onChange(function (e) {
            cube.position.x = e;
        });
        cubeFolder.add(gui,"cubeY",-30,30).onChange(function (e) {
            cube.position.y = e;
        });
        cubeFolder.add(gui,"cubeZ",-30,30).onChange(function (e) {
            cube.position.z = e;
        });
        cubeFolder.add(gui,"cubeScale",0,3).onChange(function (e) {
            cube.scale.set(e, e, e);
        });        //场景组的操作
        var groupFolder = datGui.addFolder("group");
        groupFolder.add(gui,"groupX",-30,30).onChange(function (e) {
            group.position.x = e;
        });
        groupFolder.add(gui,"groupY",-30,30).onChange(function (e) {
            group.position.y = e;
        });
        groupFolder.add(gui,"groupZ",-30,30).onChange(function (e) {
            group.position.z = e;
        });
        groupFolder.add(gui,"groupScale",0,3).onChange(function (e) {
            group.scale.set(e, e, e);
        });        //添加旋转功能
        datGui.add(gui, "grouping");
        datGui.add(gui, "rotate");
    }    var light;    function initLight() {
        scene.add(new THREE.AmbientLight(0x444444));

        light = new THREE.PointLight(0xffffff);
        light.position.set(15,50,10);        //告诉平行光需要开启阴影投射
        light.castShadow = true;

        scene.add(light);
    }    var sphere,cube,group;    function initModel() {

        //模型组
        group = new THREE.Object3D();
        scene.add(group);        //球
        var sphereGeometry = new THREE.SphereGeometry(5,200,200);        var sphereMaterial = new THREE.MeshLambertMaterial({color:0xaaaaaa});

        sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.position.x = -5;
        sphere.position.y = 5;        //告诉球需要投射阴影
        sphere.castShadow = true;

        group.add(sphere);        //辅助工具
        var helper = new THREE.AxisHelper(50);
        scene.add(helper);        //立方体
        var cubeGeometry = new THREE.CubeGeometry(10,10,8);        var cubeMaterial = new THREE.MeshLambertMaterial({color:0x00ffff});

        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.position.x = 15;
        cube.position.y = 5;
        cube.position.z = -5;        //告诉立方体需要投射阴影
        cube.castShadow = true;

        group.add(cube);        //底部平面
        var planeGeometry = new THREE.PlaneGeometry(100,100);        var planeMaterial = new THREE.MeshStandardMaterial({color:0xaaaaaa});        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.rotation.x = - 0.5 * Math.PI;
        plane.position.y = -0;        //告诉底部平面需要接收阴影
        plane.receiveShadow = true;

        scene.add(plane);

    }    //初始化性能插件
    var stats;    function initStats() {
        stats = new Stats();
        document.body.appendChild(stats.dom);
    }    //用户交互插件 鼠标左键按住旋转,右键按住平移,滚轮缩放
    var controls;    function initControls() {

        controls = new THREE.OrbitControls( camera, renderer.domElement );        // 如果使用animate方法时,将此函数删除
        //controls.addEventListener( &#39;change&#39;, render );
        // 使动画循环使用时阻尼或自转 意思是否有惯性
        controls.enableDamping = true;        //动态阻尼系数 就是鼠标拖拽旋转灵敏度
        //controls.dampingFactor = 0.25;
        //是否可以缩放
        controls.enableZoom = true;        //是否自动旋转
        controls.autoRotate = false;        //设置相机距离原点的最远距离
        controls.minDistance  = 100;        //设置相机距离原点的最远距离
        controls.maxDistance  = 200;        //是否开启右键拖拽
        controls.enablePan = true;
    }    var step = 0.02; //模型旋转的速度
    function render() {

        //判断当前是否自动旋转
        if(gui.rotate){            //判断是单个模型自转,还是模型组自转
            if(gui.grouping){
                group.rotation.y += step;
            }            else{
                sphere.rotation.y += step;
                cube.rotation.y += step;
            }
        }

        renderer.render( scene, camera );
    }    //窗口变动触发的函数
    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        render();
        renderer.setSize( window.innerWidth, window.innerHeight );

    }    function animate() {
        //更新控制器
        render();        //更新性能插件
        stats.update();

        controls.update();

        requestAnimationFrame(animate);
    }    function draw() {
        initGui();
        initRender();
        initScene();
        initCamera();
        initLight();
        initModel();
        initControls();
        initStats();

        animate();
        window.onresize = onWindowResize;
    }</script></html>
Copy after login

The above is the detailed content of Three.js uses object composition instance methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template