ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Extended Example: Steering the Car Using a Mouse | 193

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


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


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


the appropriate keys results in small turns.


Extended Example: Steering the Car Using a Mouse


If the target interface is designed with flexibility and future use in mind, the adapter


can be used in multiple contexts. Because steering is accomplished in discrete steps


using theturnMoreToTheLeft( ),turnMoreToTheRight( ), andgoStraight( )methods


implemented in the adapter, it can be used with different input devices such as a joy-


stick or mouse. Let’s look at how a client can use mouse input to steer the car. For


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


straight. How can a left and right turn be accomplished using the mouse? One way is


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


the mouse moves to the left, we can callturnMoreToTheLeft( ). If the mouse moves to


the right, we can callturnMoreToTheRight( ).


The basic client is similar to theMainclass (Example 5-12) that used keyboard input


to steer the car. The following changes need to be made to theMainclass in order to


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


previous horizontal location of the mouse on the stage, to figure out if the mouse


moved to the left or right. The initial horizontal location will be zero.


private var oldMouseStageX:Number = 0;

An additional change is to attach different listener functions that respond to mouse


events rather than keyboard events. Instead of attaching a listener function to


Figure 5-6. The interface showing mouse input


Ignition key

function start() :void

function goStraight() :void
Mouse moves to
the left
function turnMoreToTheRight() :void

function turnMoreToTheLeft() :void

Mouse click

Mouse moves to
the right
Free download pdf