JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
}
}
</script>
JavaScript
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// init
const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 100 );
camera.position.z = 10;
const scene = new THREE.Scene();
function applyWorldMatrixToGeometry(object) {
// First traversal: Apply world matrix to geometry
object.traverse(function (child) {
if (child.isMesh) {
child.updateMatrixWorld(true);
child.geometry.applyMatrix4(child.matrixWorld);
}
});
// Second traversal: Reset transformations after applying the world matrix
object.traverse(function (child) {
if (child.isMesh) {
child.position.set(0, 0, 0);
child.rotation.set(0, 0, 0);
child.scale.set(1, 1, 1);
// Optionally, recalculate the bounding box and vertex normals
child.geometry.computeBoundingBox();
child.geometry.computeVertexNormals();
}
});
}
const parentMesh = new THREE.Mesh(
new THREE.SphereGeometry(1, 32, 32),
new THREE.MeshBasicMaterial({ color: 0x0000ff })
);
const childMesh1 = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({ color: 0x00ff00 })
);
childMesh1.position.set(2, 0, 0);
const childMesh2 = new THREE.Mesh(
new THREE.CylinderGeometry(0.5, 0.5, 2, 32),
new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
childMesh2.position.set(0, 2, 0);
parentMesh.add(childMesh1);
childMesh1.add(childMesh2);
scene.add(parentMesh);
// Apply world transformations to all nested meshes
applyWorldMatrixToGeometry(parentMesh);
const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );
const controls = new OrbitControls( camera, renderer.domElement );
// animation
function animation( time ) {
//controls.update();
renderer.render( scene, camera );
}
window.onresize = () =>...