< Zurück | Inhalt | Weiter >

Java 3D and the mouse

So, all this begs the question, how does Java 3D support the standard mouse as an input device? The answer is that the behavior model again comes into play. Mouse behaviors respond to AWT events such as mouse−click, mouse−drag, and mouse−release and convert the mouse events’ x and y pixel coordinates into changes that are applied to a Transform3D, which is in turn applied to a TransformGroup. Any child Nodes beneath the TransformGroup will be moved, scaled, or rotated based on the changes in their parents’ TransformGroup.

Java 3D’s mouse behaviors are included in the Java 3D utility package (com.sun.j3d.utils.behaviors.mouse), which underscores their status as works in progress. The three basic mouse behaviors are

MouseRotate: Rotates an object when the left mouse button is pressed.

MouseTranslate: Translates an object when the right mouse button is pressed.

MouseScale: Scales an object when the left mouse button is pressed and the ALT key is held down.

The Java 3D mouse behaviors are all derived from a common base class, MouseBehavior.












Since the basic mouse behaviors are fairly easy to use, you merely create the behavior object passing in the TransformGroup that the behavior is to affect, optionally set the behavior’s scheduling bounds, add the behavior to the scenegraph, and voila! The objects underneath the TransformGroup should now move, rotate, or scale based on your mouse movements, as shown in the following code example.

//create a TransformGroup that we will be rotating TransformGroup subTg = new TransformGroup();

//The WRITE capability must be set so that the behavior can

//change the Transform3D in the TransformGroup subTg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);

//add a ColorCube as a child of the TransformGroup subTg.addChild( new ColorCube(10.0) );

//attach a MouseRotate behavior so we can rotate the color cube

//with the left mouse button

MouseRotate mouseRot = new MouseRotate( subTg ); subTg.addChild( mouseRot );

The three built−in mouse behaviors are fine for simple applications or quick prototyping; however, they have a number of drawbacks in serious applications. Section 11.7.3 will define three new mouse behaviors that fix some of these problems and provide a more robust framework to use in applications.

The Java 3D VRML viewer (see
http://www.j3d.org for details) also includes a number of mouse and keyboard behaviors and full source code. In particular, it defines behaviors appropriate for VRML world navigation:

FlightBehavior.java allows the user to fly through a 3D world, controlling roll, pitch, yaw, and velocity.

KeyBehavior.java is another keyboard navigation class.

So, don’t reinvent the wheel; consult, modify, or derive from the available navigation behaviors whenever you can.