240 | Chapter 6: Composite Pattern
Calculating the Total Weight of the Airplane
Line 56 of theMainclass shown in Example 6-25 calls thegetWeight( )method on the
root node of the airplane. The following output is the result of this statement.
Weight of airplane: 2100
ThegetWeight( )method calculates the weight iteratively by adding the weights of all
components in the airplane structure. This is a very powerful way of keeping track of
an overall parameter in a comple xcomposite structure. If this airplane were used in a
game, the weight is essential to craft realistic movement dynamics using motion
physics. The weight of the plane can change dynamically. For example, the plane
could be carrying passengers, bombs, and a fuel tank. Adding passengers will
increase weight; dropping bombs will reduce weight, and flight will progressively
reduce weight by using up fuel. ThegetWeight( )method will work exactly the same
way if we extend the airplane to add and remove other components such as passen-
gers, fuel, etc.
31 leftWing.scaleX = -1; // flip on vertical axis
32 leftWing.x = -20; leftWing.y = 50;
33 fuselage.addChild(leftWing);
34
35 // add engine to right wing
36 var rightEngine:Component = new Engine(300, 0);
37 rightEngine.x = 50; rightEngine.y = -20;
38 rightWing.addChild(rightEngine);
39
40 // add engine to left wing
41 var lefttEngine:Component = new Engine(300, 0);
42 lefttEngine.x = 50; lefttEngine.y = -20;
43 leftWing.addChild(lefttEngine);
44
45 // add tail wing on the right
46 var leftTailWing:Component = new TailWing(50, 0);
47 leftTailWing.scaleX = -1; // flip on vertical axis
48 leftTailWing.x = -20; leftTailWing.y = 150;
49 fuselage.addChild(leftTailWing);
50
51 // add tail wing on the left
52 var rightTailWing:Component = new TailWing(50, 0);
53 rightTailWing.x = 20; rightTailWing.y = 150;
54 fuselage.addChild(rightTailWing);
55
56 trace('Weight of airplane: ' + airPlane.getWeight( ));
57 //total weight
58 }
59 }
60 }
Example 6-25. Main.as (continued)