I'd like to do be able to detect if an object is in shadow or not. What would be the best, most performant way to do this?
Eg., There's a tree in the scene and a directional light. Move a character under the tree and they are now standing in the tree'a shadow which it casts. How can you detect at what point they have entered / left the tree's cast shadow?
This is not the ultimate solution, this is just an option you can use as the start point.
And this is just a translation of my answer from another segment of stackoverflow.com, dedicated to Three.js.
The idea: you set a ray from the point along the direction to a light source, and, if it intersects any object, then the point is in the shadow, otherwise, it's not.
Given: point on a plane pointOnPlane
, a normalized vector of the position of a directional light source (which will be our direction) direction
and an array of objects in the scene sceneObjects
(which we want to find intersection with). To determine, if the point is shaded or not, we'll need a short function:
var raycasterPoint = new THREE.Raycaster();
var direction = new THREE.Vector3();// for re-use
function isShaded(pointOnPlane){
direction.copy(light.position).normalize();
raycasterPoint.set(pointOnPlane, direction); // ray's origin and direction
var retVal = false;
var pointIntersects = raycasterPoint.intersectObjects( sceneObjects );
if (pointIntersects.length > 0) retVal = true;
return retVal;
}
jsfiddle example.