ABSTRACT

There are Boolean values for each key we’ll use so we can know whether or not that key is being pressed. There is also a value for friction or, rather, the coeffi cient of friction of the surface the vehicle will be driving on. This value will cause the vehicle to slow down when it is not accelerating:

When the game is added to the Stage, it triggers startGame. This method sets up listeners for both keyboard input and the enterFrame cycle. We’ll look at the keyDown and keyUp methods next:

These two functions simply toggle the different Boolean values to either true or false as keyboard input is received:

Because we’re dealing with keyboard input, which automatically focuses on the Stage, on each frame cycle we make sure that the game still has focus, even if the player were to click somewhere

else on the screen. The class then calls readInput and moveVehicle , both of which we’ll look at next:

This method runs through all the key-related Boolean values. If the up or down arrows are pressed, it applies acceleration. If the right and left arrows are pressed, it applies steering based on the speed of the vehicle. Finally, if the space bar is pressed, it applies the hand brake friction to the vehicle’s speed and resets any acceleration:

Although only four lines, this method does a great deal. First, it applies friction to the vehicle’s speed if it is not accelerating; not doing so would cause the vehicle to continue moving as though it were on a very slick surface. The vehicle’s speed is then increased by its acceleration. The last two lines then compute the vehicle’s new x and y coordinates based on the angle the car is facing and the speed at which it is traveling. Note that both this method and the readInput method make use of the Time.deltaTime property to only apply the speed that is necessary for the amount of time that has passed. By using this method, the frame rate of the SWF can now change, either deliberately or accidentally, without consequence to the responsiveness of the simulation.