Hey there, I've been diving into three.js recently and managed to successfully import a 3D model from Cinema 4D using the three.OBJMTLLoader. However, I'm having trouble getting the imported object to cast a shadow. I've tried setting object.castShadow = true, but it doesn't seem to be working. Interestingly, I can get geometries created in three.js to cast shadows, so I know the scene setup is correct.
You can check out the test scene here: . I've also updated it with the suggested fix below.
Below is the code. If anyone could kindly point out where I might be going wrong or confirm if imported objects can cast shadows, I would truly appreciate it.
Cheers.
<script>
var container;
var controls;
var camera, scene, renderer;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
camera.position.z = 500;
camera.position.y = 500;
scene = new THREE.Scene();
controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
var ambientLight = new THREE.AmbientLight(0x0c0c0c);
scene.add(ambientLight);
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(500, 1000, 500);
spotLight.castShadow = true;
spotLight.shadowMapWidth = 1024;
spotLight.shadowMapHeight = 1024;
scene.add(spotLight);
var companion = new THREE.OBJMTLLoader();
companion.load('companion2.obj', 'companion.mtl', function (object) {
object.position.set(0, -20, 0);
object.scale.set(0.8, 0.8, 0.8);
object.castShadow = true;
scene.add(object);
});
var floorGeometry = new THREE.CubeGeometry(1000, 4, 1000);
var floorMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 });
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.position.set(0, -130, 0);
floor.receiveShadow = true;
scene.add(floor);
var geometry = new THREE.BoxGeometry(100, 100, 100);
mesh = new THREE.Mesh(geometry);
scene.add(mesh);
mesh.position.set(-100, 200, 10);
mesh.castShadow = true;
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xEEEEEE, 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
spotLight.shadowCameraVisible = true;
var step = 0;
render();
};
function render() {
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
</script>