A raycaster (or raypicking) is used to interact with 3D objects from the camera point of view. The raycaster achieves this by casting a line that follows the camera frustum checking for collisions with 3D meshes along the way.
In nunuStudio every scene has a raycaster by default using the first camera to render. The raycaster attached to the scene is updated everyframe with the mouse coordinates.
The code bellow can be used to test the raycaster object, we start by getting the red and blue materials from the program. On the update method we use the raycaster intersectObjects method to check if the mouse is on top of some object.
After we get the list of intersected objectes we loop though them and change their material depending on which mouse button is currently pressed.
var red, blue;
function initialize()
{
red = program.getMaterialByName("red");
blue = program.getMaterialByName("blue");
}
function update()
{
//Check interseted objects
var intersects = scene.raycaster.intersectObjects(scene.children);
//Intersections list contains object, point of intersection, distance, uv and face
for(var i = 0; i < intersects.length; i++)
{
if(Mouse.buttonPressed(Mouse.LEFT))
{
intersects[i].object.material = red;
}
else if(Mouse.buttonPressed(Mouse.RIGHT))
{
intersects[i].object.material = blue;
}
}
}
The intersectObjects method returns a list of intersection objects, each intersection object has the following attributes. To raycast a single object is also possible to use the intersectObject method that only returns a single intersection object.
distance – distance between the origin of the ray and the intersection
point – point of intersection, in world coordinates
face – intersected face
faceIndex – index of the intersected face
indices – indices of vertices comprising the intersected face
object – the intersected object
uv - U,V coordinates at point of intersection
Intersections are sorted by distance, the first object in the intesection list is always the one closer to the camera. If everything worked as expected you should have something similar to the demo bellow. Use the left mouse button to paint the cubes blue and the right mouse button to paint them red.
To try this example in the editor you can download the project file or open it on the Web Editor.
A simpler way to use the raycaster is to declare a onMouseOver(intersects) method in the script. This method is automatically called when the mouse is over one of the children of that script.
function onMouseOver(intersects)
{
console.log(intersects);
}