Detecting a Miss
We now add code to the ball instance that detects when the ball has moved outside of the stage. First, add the checkBall function in Fig. 17.18 to the second frame of the Actions panel.
Lines 5–6 test whether the ball is outside the bounds of the stage. If it is, the checkBallTimer is stopped (line 8), because the ball is no longer in motion and does not need to be checked until it has been fired again. Boolean firing is set to false (line 9). Then, lines 10–12 play the text movie clip’s miss frame, the scoreText movie clip’s minusTwo frame and the sound movie clip’s miss frame. This will display MISS and -2 on the stage, and play the miss sound. Also, the timer variable is decreased by 2 (line 13). Finally, the Ball object is reset to its starting position and speed (lines 14–17).
In order to check the ball at regular intervals, we create a timer that calls checkBall every 33 ms. First, add the following code to the second frame of the Actions layer:
// Check ball at 33-ms intervals
var checkBallTimer : Timer = new Timer( 33, 0 );
1 // Fig. 17.18: Detecting a miss.
2 function checkBall ( e : TimerEvent )
4 // if ball is not inside stage, go through miss sequence
5 if ( ( ball.x < 0 ) || ( ball.y < 0 ) || ( ball.x > 550 ) ||
6 ( ball.y > 400 ) )
8 checkBallTimer.stop(); // stop checkBallTimer
9 firing = false; // ball is no longer being fired
10 text.gotoAndPlay( "miss" ); // display miss on the stage
11 scoreText.gotoAndPlay ( "minusTwo" ); // display "-2"
12 sound.gotoAndPlay ( "miss" ); // miss sound is played
13 timer -= 2; // deduct 2 seconds from timer
14 ball.x = 0; // set ball back to initial x-coordinate
15 ball.y = 200; // set ball back to initial y-coordinate
16 ball.setSpeedX( 0 ); // set ball speed in x-direction to 0
17 ball.setSpeedY( 0, 0 ); // set ball speed in y-direction to 0
18 } // end if
} // end function checkBall
Fig. 17.18 | Detecting a miss
Next, we must start the timer. Since this timer needs to run only after the ball has been fired, we will start the timer in the mouseDownHandler. Insert the following code between lines 13 and 14 of Fig. 17.13.
// call function checkBall as checkBallTimer event handler checkBallTimer.addEventListener( TimerEvent.TIMER, checkBall ); checkBallTimer.start(); // start Timer
We must also stop this timer at the end of the game by adding the following code to the third frame of the Actions layer.
Test the movie with your computer’s sound turned on. At this point, every fired ball should travel off the stage and count as a miss. In the next few sections, we discuss how to add features that allow the player to gain time and win the game.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.