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 shadows not working properly
How to create directional light shadow in Three.JS?
答案 0 :(得分:3)
首先,在场景中添加一个摄像头控制器,以便您可以看到自己在做什么。现在,您可以旋转相机以获得不同的视图。
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;
对于方向灯,只有&#34;指向&#34;光的位置很重要。但是,当涉及阴影贴图时,灯光的实际位置很重要,因为它也会控制阴影摄影机。
light.position.set( -60, 20, 100 );
这是一个更新的小提琴。用鼠标旋转相机。
three.js r.66
答案 1 :(得分:1)
将这些添加到灯光定义中:
light.shadowMapWidth =
light.shadowMapHeight = 1024;
light.shadowCameraNear = 1;
light.shadowCameraFar = 100;