Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Your Email:

Flash Race Car Tutorial

By Matt Carpenter
2007-12-15


Start your engines

The first step is to set up the car’s controls. To allow keyboard buttons to control the car, we need to create a KeyListener object. The KeyListener catches key press and release events similar to the way Flash Button object catches the mouse press and release events. When a key is pressed or released the KeyListener will see that event and show us what key the action happened on. We will program the listener to only pay attention to the arrow keys and call the appropriate function on our car when one is pressed or released.

We are setting up the KeyListener to alert us when the control keys are pressed and when they are released. For instance, when the UP arrow key is pressed, the car will accelerate until it is release. By listening for both the Press action and the Release action we will be able to control the car. I won’t bore you too much with all of the details of how the KeyListener works. Instead I’ll throw you the code and let you see it yourself.

Sidenote:
When I’m debugging KeyListeners, I usually put trace statements in my code to make sure the right functions are linked to the right keys. Add trace statements when you are first writing up the code to save yourself a lot of headaches.

// Create key listener
var keyListener:Object = new Object();
keyListener.onKeyDown = function () {
switch ( Key.getCode() ) {
case Key.UP:
_root.mainCar.ForwardOn();
break;
case Key.DOWN:
_root.mainCar.ReverseOn();
break;
case Key.RIGHT:
_root.mainCar.RightTurnOn();
break;
case Key.LEFT:
_root.mainCar.LeftTurnOn();
break;
}
}
keyListener.onKeyUp = function () {
switch ( Key.getCode() ) {
case Key.UP:
_root.mainCar.ForwardOff();
break;
case Key.DOWN:
_root.mainCar.ReverseOff();
break;
case Key.RIGHT:
_root.mainCar.RightTurnOff();
break;
case Key.LEFT:
_root.mainCar.LeftTurnOff();
break;
}
}
Key.addListener(keyListener);


Tutorial Pages:
» Making a car
» Start your engines
» Let's burn some rubber


 | Bookmark
Related Tutorials:
» Flash Momentum Tutorial
» Customized Cursor in Flash MX 2004
» Dropdown Menu in Flash MX 2004
» How to Change the Movie Visibility Using Action Script in Flash MX 2004
» Changing Colors for the Flash Movie in Flash MX 2004
» Using Symbols in Flash