Table of Contents
Implementation of object combination
Case code
Home Web Front-end JS Tutorial Three.js uses object composition instance methods

Three.js uses object composition instance methods

Mar 14, 2018 pm 05:32 PM
javascript Example

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles