Today, I found that the projection of. obj model in threejs is a little different from that of geometry. Write an article to record it to prevent forgetting, and I hope it can help you!
If it helps your problem, please like it.~
Principle:
The projection method of obj model is to traverse the elements in obj.children and set them: castShadow and receiveShadow;
Core code:
for(k in obj.children){ obj.children[k].castShadow = true; obj.children[k].receiveShadow = true; }
Create the complete code for the model:
// Generate car model function initCar(){ var geometry, material; var loader = new THREE.MTLLoader(); loader.setPath('../3d-models/'); loader.load('car.mtl', function(material){ material.preload(); let objLoader = new THREE.OBJLoader(); objLoader.setMaterials(material); objLoader.load('../3d-models/car.obj', function(obj){ for(k in obj.children){ obj.children[k].castShadow = true; obj.children[k].receiveShadow = true; } // obj.receiveShadow = true; / / this method has no effect and only applies to geometry model. // obj.castShadow = true; / / this method has no effect and only applies to geometry model. scene.add(obj); }) }) }
Code projected by geometry projection model: (compare with. obj code)
function initCube(){ var geometry = new THREE.BoxGeometry(20, 20, 20); var material = new THREE.MeshPhongMaterial({ color: 0xff3300 }); cube = new THREE.Mesh(geometry, material); cube.receiveShadow = true; // Contrast.obj cube.castShadow = true; // Contrast.obj scene.add(cube) }
Analyze it carefully:
In fact, when adding shadows to the model, we set castShadow and receiveShadow on the Mesh object, while the. Obj object is composed of many meshes, all of which are in obj.children, so we need to traverse obj.children to add shadow effects.