Subtleties and best practices
<>
iconname
to your objectsso that you can use getObjectByName
scene.getObjectByName('name')
It also makes debugging easier.
:warning: Slow method, do not use during the animation loop. :point_right: Retrieve the object once and store it in a variable
userData
is your friendYou can store anything in it, here are a few examples:
obj.userData.velocity.x = ...
See https://threejs.org/examples/webxr_xr_cubes.html
obj.userData.isSelecting = true
See https://threejs.org/examples/webxr_xr_sculpt.html
userData.physicsBody
See https://threejs.org/examples/physics_ammo_cloth.html
object.userData.mass
See https://threejs.org/examples/physics_ammo_break.html
console.log(renderer.info.render.calls)
Group
your objectsConsider this as a single matrix, an empty object with children but no geometry
applyMatrix4
on geometry:warning: Slow! Modifies the vertex buffer!
lookAt
for easy rotationsOften used for the camera but can be used for any object.
See the last part of https://threejs.org/manual/#en/scenegraph
obj.visible
traverse
object.traverse / scene.traverse
if(child.isMesh) child.material.map = ...
obj.children.includes
or other Array methodsobj.position.set
obj.rotateX
obj.position.distanceTo // most basic collision detection
const mesh = new THREE.Mesh(geometry, createMaterial());
geometry.computeBoundingBox();
geometry.boundingBox.getCenter(mesh.position).multiplyScalar(-1);
See https://threejs.org/manual/#en/primitives (search textgeometry)
Example:
const position = geometry.attributes.position;
position.usage = THREE.DynamicDrawUsage;
for ( let i = 0; i < position.count; i ++ ) {
const y = 35 * Math.sin( i / 2 );
position.setY( i, y );
}
See
https://sbcode.net/threejs/geometry-to-buffergeometry/
https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_dynamic.html
You can draw thusands copies of the same object for free!
See instancing example: https://threejs.org/examples/webgl_instancing_performance
import TWEEN from 'three/addons/libs/tween.module.js';
Tutorial:
https://sbcode.net/threejs/tween/
See https://threejs.org/manual/#en/cleanup
See https://threejs.org/examples/webgl_lights_hemisphere
:warning: Objects are referenced, not copied by default.
Use clone()
Define and reuse temp vectors, quaternions, matrices
Local matrix: relative to parent World matrix: relative to scene
https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language
glsl
webgpu
)(function printGraph( obj ) {
console.group( ' <%o> ' + obj.name, obj );
obj.children.forEach( printGraph );
console.groupEnd();
} ( scene ) );
See https://github.com/mrdoob/three.js/issues/10961