Firing the BeamThe FireBeam tHRead is started from updateScene( ) like so: new FireBeam(intercept, this, laser, explsClip, turnAngle).start( ); A basic question is why use a thread? One answer is that by passing the job of beam delivery and explosion to a new thread, the ShootingBehaviour object is free to do other tasks. For example, it could show a puff of animated smoke rising from the gun's cone or have the cone recoil slightly. Shooter3D doesn't do these things, as that would further complicate the example. At present, the threaded implementation allows updateScene( ) to process a user's new pick selection once the finishedShot Boolean has been set to true near the end of run( ) in the FireBeam thread: public void run( ) { laser.shootBeam(intercept); shooter.setFinishedShot( ); // beam has reached its target explsClip.showExplosion(turnAngle, intercept); // boom! } The call to setFinishedShot( ) sets finishedShot to TRue, which permits updateScene( ) to respond to user clicks and, simultaneously, the explosion for the current beam will be initiated from FireBeam. This improves the responsiveness of the application since the explosion animation lasts one to two seconds. However, there's a problem: what if the explosion animation for the beam (i.e., the current call to showExplosion( )) doesn't finish before the FireBeam thread for the next beam calls showExplosion( ) again? The worst that happens is an interruption to the explosion animation and the truncation of the playing of the sound. However, in the vast majority of situations, the travel time of the laser beam and the explosion animation duration means that the explosion finishes before it's required again. From a practical point of view, this may be sufficient, but in the next chapter you'll see a better coding approach that allows multiple beams and multiple explosions to coexist safely on screen at the same time. |