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 ...