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); //将对象组添加到场景当中
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( 'change', 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>
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!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools
