var camera, scene, renderer;
var cubes = [];
init();
animate();
function init() {
scene = new THREE.Scene();
scene.add(new THREE.AmbientLight(0x212223));
for (var i = 0; i < 10; i++) {
var cubeGeometry = new THREE.CubeGeometry(1, 1.5, 1);
var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0x1ec876 });
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.set(i*1.2, 0, 0.5);
cube.castShadow = true;
scene.add(cube);
cubes.push(cube);
}
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.x = -4;
camera.position.y = -4;
camera.position.z = 20;
camera.lookAt(cubes[5].position);
scene.add(camera);
var terrainGeo = new THREE.PlaneGeometry(50, 50);
var terrainMaterial = new THREE.MeshLambertMaterial({ color: 0xc0c0a0 });
var terrain = new THREE.Mesh(terrainGeo, terrainMaterial);
terrain.receiveShadow = true;
scene.add(terrain);
var light = new THREE.DirectionalLight(0xffffff, 1);
light.castShadow = true;
light.shadowCameraVisible = true;
light.position.set(-3, 1, 5);
scene.add(light);
scene.add( new THREE.DirectionalLightHelper(light, 0.2) );
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = false;
document.body.appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
for (var i = 0; i < cubes.length; i++) {
cubes[i].rotation.x += 0.01 * i;
cubes[i].rotation.y += 0.02 * i;
}
renderer.render(scene, camera);
}
为什么阴影不起作用?
我看了相关的问题和three.js参考,但不明白我做错了什么。
Three.js shadows not working properly
How to create directional light shadow in Three.JS?
ThreeJS shadow not rendering
http://threejs.org/docs/#Reference/Lights/DirectionalLight
http://learningthreejs.com/blog/2012/01/20/casting-shadows/
最佳答案
首先,将摄像机控制器添加到场景中,以便可以看到正在执行的操作。现在,您可以旋转相机以获得不同的视图。
controls = new THREE.OrbitControls( camera, renderer.domElement );
其次,在使用jsfiddle时,请确保链接到three.js库的最新版本。
<script src="http://threejs.org/build/three.min.js"></script>
为了获得适当的分辨率,将阴影摄像机紧紧固定在场景中非常重要。您可以通过设置以下内容来做到这一点:
light.shadowCameraLeft = -20; // or whatever value works for the scale of your scene
light.shadowCameraRight = 20;
light.shadowCameraTop = 20;
light.shadowCameraBottom = -20;
对于定向灯,仅“指向”灯位置的“方向”很重要。但是,当涉及阴影贴图时,光线的实际位置很重要,因为它也控制阴影相机。
light.position.set( -60, 20, 100 );
这是更新的小提琴。用鼠标旋转相机。
http://jsfiddle.net/wp6E3/4/
three.js r.66