Moving the Viewpoint


Managing the Ammunition

A drawback of the shooting application in Chapter 23 is that only one laser beam can appear at a time, and if another explosion is triggered before the previous one has finished, then the animation (and sound effects) may be disrupted. My AmmoManager class fixes these problems by creating a collection of beams and explosions; several beam or explosions can appear at the same time because they're represented by different objects.

Each beam and explosion is represented by a LaserShot object, and AmmoManager's constructor creates NUMBEAMS of them (20) and adds them to the scene:

     public AmmoManager(TransformGroup steerTG,                   BranchGroup sceneBG, Vector3d targetVec)     {       // load the explosion images       ImageComponent2D[] exploIms = loadImages("explo/explo", 6);           shots = new LaserShot[NUMBEAMS];       for(int i=0; i < NUMBEAMS; i++) {         shots[i] = new LaserShot(steerTG, exploIms, targetVec);         // a LaserShot represents a single beam and explosion         sceneBG.addChild( shots[i].getTG(  ) );       }      } 

An explosion animation uses six GIFs, and it would be inefficient if each LaserShot object loaded those images. It's much better to load the images once into an array (exploIms) and pass a reference to that array to each object. In this way each LaserShot object uses the same animation.

Shooting the Gun

A beam is fired from the gun when the user presses the f key. The KeyBehavior object captures the key press and calls fireBeam( ) in AmmoManager.

AmmoManager's managerial role is to hide that there are NUMBEAMS LaserShot objects and, instead, offers a single fireBeam( ) method, which fires a beam if one is available:

     public void fireBeam(  )     { for(int i=0; i < NUMBEAMS; i++) {         if( shots[i].requestFiring(  ) )           return;       }     } 

The requestFiring( ) method returns true if the beam is free and has been set in motion. It returns false if the beam is already in use (i.e., traveling or exploding).

It's possible for all the LaserShot objects to be busy when the user types f and for nothing to happen. In practice, this situation is unlikely to occur because a beam is busy for no more than 3 to 4 seconds, and 20 LaserShot objects are available. From a gaming point of view, the possibility of running out of beams, albeit temporarily, may make the game play more interesting.



Killer Game Programming in Java
Killer Game Programming in Java
ISBN: 0596007302
EAN: 2147483647
Year: 2006
Pages: 340

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net