ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Car Steering Adapter | 187

The parameterized constructor (lines 13-19) gets the initial location of the car


throughxLocandyLocparameters. The constructor sets the propertynSpeedto its


default value of 5, and setsnSteeringWheelAngleto zero indicating that the steering


wheel is held straight. It then calls thedrawCar( )method to draw the car, and the


setLoc( ) method with the passed x and y coordinates to place theSprite.


ThedrawCar( )method (lines 21-32) uses thegraphicsproperty of theSpriteclass to


draw the car from the perspective of looking down on it from above (map view). The


car is a green rectangle with four black wheels (also rectangles) drawn using the


47 }

48

49 // method to attach event handlers and get the car moving
50 public function start( ):void
51 {
52 if (this.stage)
53 {
54 // attach EnterFrame event handler doMoveCar( )
55 this.addEventListener(Event.ENTER_FRAME, this.doMoveCar);
56 } else {
57 throw new Error("Add car to display list first")
58 }
59 }
60
61 // method to set the steering wheel angle (in Degrees)
62 public function setSteeringWheelAngle(nAngle:int):void
63 {
64 nSteeringWheelAngle = nAngle;
65 }
66
67 // move the car
68 private function doMoveCar(event:Event):void
69 {
70 this.rotation += nSteeringWheelAngle * 0.01; // rotate sprite
71 trace(nSteeringWheelAngle);
72 var newLocOffset:Point = Point.polar(nSpeed,
73 this.rotation * Math.PI / 180);
74 this.x += newLocOffset.x; // move by the x offset
75 this.y += newLocOffset.y; // move by the y offset
76 // place Sprite in center of stage if it goes off screen
77 if ((this.y < 0) || (this.y > this.stage.stageHeight) ||
78 ((this.x < 0)) || (this.x > this.stage.stageWidth))
79 {
80 this.setLoc(this.stage.stageWidth * 0.5,
81 this.stage.stageHeight * 0.5);
82 }
83 }
84 }
85 }

Example 5-9. LegacyCar.as

Free download pdf