ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Using Flash’s Built-in Composite Structure: the Display List | 241

Modifying Components to Reflect Damage


We will modify the composite components of the airplane to increase their damage


property when clicked by the mouse. In a realistic game scenario, the source of dam-


age will be bullets, missiles and random malfunctions in components. However, in


the interest of keeping things simple, we’ll imagine that a mouse click is a bullet hit.


In Example 6-26 we will modify the Fuselage (Example 6-21) and MainWing


(Example 6-22) classes to respond to mouse clicks.


Line 13, in the modifiedFuselageclass constructor (Example 6-26), registers the


doDamage( )method to receive mouse click events. ThedoDamage( )method simply


increments the nDamage property defined in the superclass by 10. The


stopPropagation( )event call in line 22 is important to isolate event responses to


embedded display objects such as this. If not, the event would propagate up the dis-


play list running other registered click event handlers in parent nodes. This state-


ment ensures that the lowermost registered node in the clicked branch of the display


list hierarchy handles the event. The ActionScript 3.0 documentation has more


details on event propagation. In Example 6-27, we will now modify theMainWing


class to exhibit similar behavior.


Example 6-26. Fuselage.as with modifiedFuselage class


1 package
2 {
3 import flash.events.*;
4
5 public class Fuselage extends Composite
6 {
7 public function Fuselage(weight:Number, damage:Number = 0)
8 {
9 graphics.lineStyle(40, 0xC0C0C0);
10 graphics.moveTo(0, 0);
11 graphics.lineTo(0, 150);
12
13 addEventListener(MouseEvent.CLICK, doDamage);
14
15 super(weight, damage);
16 }
17
18 private function doDamage(evt:Event)
19 {
20 this.nDamage += 10;
21 trace('Damage to the fuselage is now ' + this.nDamage);
22 evt.stopPropagation( ); // stop event propegation
23 // to subsequent nodes
24 }
25 }
26 }
Free download pdf