Picking with a Mouse Click
Picking projects a pick shape (usually a line or ray) into the scene from the user's viewpoint through the mouse pointer position on screen until it intersects with a shape in the scene (see Figure 23-3).
Java 3D's PickCanvas
class is used to turn a mouse click into a ray (a PickShape
object). Java 3D finds the pickable shapes that intersect with the PickShape
object, returning them as a list of PickResult
objects. Returning the PickResult
object closest to the viewer is possible.
A single PickResult
may contain many PickIntersection
objects, which hold the data for each intersection of the shape (e.g., the ray may go through the front and back face of a shape, leading to two intersection points).
The complexity of the picking coding is somewhat alleviated by using Java 3D's PickMouseBehavior
utility class, a subclass of Behaviour
, which hides much of the picking mechanism. The general format for a subclass of PickMouseBehavior
is given in Example 23-1.
Example 23-1. A typical PickMouseBehavior subclass
import javax.media.j3d.*; import com.sun.j3d.utils.picking.PickTool; import com.sun.j3d.utils.picking.PickResult; import com.sun.j3d.utils.picking.behaviors.PickMouseBehavior; // other imports as necessary... public class ExamplePickBehavior extends PickMouseBehavior { public PickHighlightBehavior(Canvas3D canvas, BranchGroup bg, Bounds bounds) { super(canvas, bg, bounds); setSchedulingBounds(bounds); pickCanvas.setMode(PickTool.GEOMETRY_INTERSECT_INFO); ...
Get Killer Game Programming in Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.