Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - How to create directional light shadow in Three.JS?

Is it possible to create shadows from a DirectionalLight?

If I use SpotLight then I see a shadow, but if I use DirectionalLight it doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Be aware that shadow maps are scale dependent. I'm working on a scene where the unit distance represents one metre, and my objects are around 0.4 metres large. This is quite small by Three.js standards. If you have this situation too, then you can take a few important steps:

  • Ensure the shadow camera's near/far planes are reasonable given your scene's dimensions.
  • Ensure the shadow camera top/left/bottom/right values are not too large, otherwise each shadow 'pixel' may be so large that you don't even notice the shadow in your scene.

Let's look at how to do this.

Debugging

Be sure to turn on the debug rendering per light via CameraHelper:

scene.add(new THREE.CameraHelper(camera)) 

Or in older versions of the Three.js:

light.shadowCameraVisible = true;

This will show you the volume over which the shadow is being calculated. Here is an example of what that might look like:

image

Notice the near and far planes (with black crosses), and the top/left/bottom/right of the shadow camera (outer walls of the yellow box.) You want this box to be tight around whatever objects you are going to have in shadow — possibly even tighter than I'm showing here.

Code

Here are some snippets of code that might be useful.

var light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 2, 2);
light.target.position.set(0, 0, 0);
light.castShadow = true;
light.shadowDarkness = 0.5;
light.shadowCameraVisible = true; // only for debugging
// these six values define the boundaries of the yellow box seen above
light.shadowCameraNear = 2;
light.shadowCameraFar = 5;
light.shadowCameraLeft = -0.5;
light.shadowCameraRight = 0.5;
light.shadowCameraTop = 0.5;
light.shadowCameraBottom = -0.5;
scene.add(light);

Make sure some object(s) cast shadows:

object.castShadow = true;

Make sure some object(s) receive shadows:

object.receiveShadow = true;

Finally, configure some values on the WebGLRenderer:

renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(canvasWidth, canvasHeight);
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...