O'Reilly logo

ActionScript 3.0 Design Patterns by Chandima Cumaranatunge, William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Example: Cars

In this example, we will develop a simple car using the MVC pattern that can be controlled from the keyboard. The emphasis will be on developing custom views using ActionScript as opposed to using built-in components. We will also see how simply changing the controller can turn a car that responds to keyboard input into one that chases another car. Casual game developers will find this example useful for game design. Figure 12-7 shows the final iteration of the example application.

Car example showing views and chase car

Figure 12-7. Car example showing views and chase car

The Model

Let's first develop the interface for our car model. We should be able to set its location on the stage and steer it by simply changing its rotation angle. We will also declare methods to set its color. Example 12-22 shows the ICar interface.

Example 12-22. ICar.as

package
{
    import flash.geom.Point;
    import flash.events.IEventDispatcher;

    public interface ICar extends IEventDispatcher {
    {
        function setLoc(pt:Point):void;
        function getLoc():Point;
        function setColor(color:uint):void;
        function getColor():uint;
        function addToRotationAngle(nAngle:int):void;
        function getRotation():int;
    }
}

The CarModel class shown in Example 12-23 implements the ICar interface. The car will move at a constant speed in the forward direction. Note that the model updates the car position using a timer.

Example 12-23. CarModel.as

package { import flash.events.*; import ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required