10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Note that the new interface turns the car in discrete steps (50 degrees on each key<br />

press). Therefore, to make a hard turn right, the right arrow key should be pressed<br />

and held down (to generate multiple key down events). A quick press and release of<br />

the appropriate keys results in small turns.<br />

Extended Example: Steering the Car Using a Mouse<br />

If the target interface is designed with flexibility and future use in mind, the adapter<br />

can be used in multiple contexts. Because steering is ac<strong>com</strong>plished in discrete steps<br />

using the turnMoreToTheLeft( ), turnMoreToTheRight( ), and goStraight( ) methods<br />

implemented in the adapter, it can be used with different input devices such as a joystick<br />

or mouse. Let’s look at how a client can use mouse input to steer the car. For<br />

example, we can use a mouse click to straighten the steering and make the car go<br />

straight. How can a left and right turn be ac<strong>com</strong>plished using the mouse? One way is<br />

by keeping track of the horizontal movement of the mouse as shown in Figure 5-6. If<br />

the mouse moves to the left, we can call turnMoreToTheLeft( ). If the mouse moves to<br />

the right, we can call turnMoreToTheRight( ).<br />

Mouse moves to<br />

the left<br />

Ignition key<br />

Mouse click<br />

Mouse moves to<br />

the right<br />

Figure 5-6. The interface showing mouse input<br />

The basic client is similar to the Main class (Example 5-12) that used keyboard input<br />

to steer the car. The following changes need to be made to the Main class in order to<br />

steer the car using the mouse. We need to add a new property to keep track of the<br />

previous horizontal location of the mouse on the stage, to figure out if the mouse<br />

moved to the left or right. The initial horizontal location will be zero.<br />

private var oldMouseStageX:Number = 0;<br />

function start() :void<br />

function goStraight() :void<br />

function turnMoreToTheRight() :void<br />

function turnMoreToTheLeft() :void<br />

An additional change is to attach different listener functions that respond to mouse<br />

events rather than keyboard events. Instead of attaching a listener function to<br />

Extended Example: Steering the Car Using a Mouse | 193

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!