Cyber Monday Sale 40% off unlimited courses & creative assets! 40% off unlimited assets! Save Now
  1. Code
  2. Games

Building a Simple Driving Game with ActionScript 3.0

Read Time:19 minsLanguages:

In this tutorial I'll be going through the steps needed to build a simple driving program. You'll learn how to add keyListeners, eventListeners and a couple of other things using ActionScript 3.0. I originally wrote this program in ActionScript 2.0 and in this tutorial I'll compare the two ActionScript versions as we go along. This should therefore make for an easy tutorial to start moving your way over to ActionScript 3.0.

Step 1: Setting Up the File

Open up a new Flash ActionScript 3.0 document, go to the Properties window (if it's not open go to Window > Properties) and click edit. Change the FPS to 50, the width to 1200px and the height to 800px.

In the timeline window (Window > Timeline) create two more layers, so there are three in total, then name the three: actions, speed, car. Lock the actions layer.

Step 2: Importing the Car Images

In the source files you'll find these three files:

  • carLeft.png
  • carRight.png
  • carStraight.png

Select the car layer and go to File > Import > Import to Stage and import the carStraight image.

Step 3: Making the Car MovieClip

Select the image and press F8, or Modify > Convert to Symbol. Leave all the settings as their defaults (top-left justified and a movieclip) and name it carMC.

Give the movieclip an instance name of carMC in the Properties window.

Double-click the image, or Rightclick > Edit. Select the image of the car and give it the coordinates x:-100, y:-230.

These can be changed to your liking, but I thought that these seemed to work the best and made the car turns look the most realistic.

Create two more keyframes after the current one.

Select the second keyframe, delete the image of the car and go to File > Import > Import to Stage and import the carLeft image. Then position it at -100,-230.

Do the same thing for the third keyframe and import the carRight image. Position that at -100,-230 as well.

Go into the actions of each keyframe (select the keyframe and hit F9 or Rightclick > Actions) and type in:

Now double-click anywhere where there is nothing, or click on Scene 1 in the top left, to go back to the main artboard.

Because the car is so large compared to the stage, select the carMC and change its width to 100px and height to 189px. This scales down all three images, but allows you to bring the size back up if you need to later.

Next, select the carMC and center it on the stage using the align window.

So far we've set the file up, made a movieclip with three frames, each with an image in it and a stop(); command.

Step 3: Adding the Speedometer

When controlling the car there'll be an indicator on the screen telling you how fast it is going.

Grab the text tool and in your Properties panel (Window > Properties) make sure it says Dynamic Text, not Static or Input Text. Click anywhere on the artboard, where you would want the speedometer to be placed (I chose bottom left) and click. This should make a text box that is about 100 px wide. If it doesn't, or if this isn't wide enough, you can adjust it to a bigger size. Go back to the Properties panel and give the dynamic text and instance name of "speedometer".

Step 4: Taking a Look at all the Code

First I'll give you all the code so you can look over it and then I'll go through it piece by piece explaining it.

Step 5: Adding Variables

Click on the first frame of the actions layer that you locked earlier and press F9 (or Right click > Actions). Add the code in here.

These are the variables we will need.

Step 6: Listening for Keypresses

The explanations are all here, except posNeg which I'll explain later.

When moving over to AS3 this was one of the more confusing parts for me. In AS2 creating functions to be called was much easier to code. You would usually just have an "if" statement inside an onEnterFrame function that looked to see if _____ key was down. In AS3 there is a way to do this similarly, but it doesn't work well with games. The movements aren't smooth and you cannot press two keys at a time.

I did it here with booleans. For my game I'm only looking to see if four keys are pressed: Up, Left, Right, and Space, so I created a boolean for each of them. I then added three listeners.

This code is pretty much equivalent to onEnterFrame. On every frame (so in our case 50 times a second) it performs the function onEnterFrameFunction. The reason being because it will allow us to continually update variables, like speed, whilst also checking if a key has been pressed (which it does indirectly through a boolean, as you'll see in a second).

These are two listeners that are added to the stage. What they do is when a key (any key) is pressed, the function keyPressed gets called. When a key is released, the function keyReleased is called.

This code comes at the end of my code, but I am explaining it now because it concerns key presses.

These are the two functions keyPressed and keyReleased. Like I said above, when a key is pressed keyPressed gets called. It checks the four "if" statements to see if the key pressed is any of the four keys my program is looking for. If the key is one of them, it sets the boolean of that key to true.

What keyReleased does is the opposite. When a key is released it checks to see if it is one of the four keys. Should this be the case, it will set the boolean of that key back to false.

Step 7: Understanding How Moving the Car Works

If we were coding a game where hitting the left key moved the car in the -x direction, and hitting the up key moved the car in the +y direction, things would be much simpler. This program is different. As there is no built in function in Flash which will move the car forward based on its current direction, we must create it ourselves. While making this code I had to do a lot of trial and error and I found that working backwards helped the most. I knew that when the card was facing N, or 0 degrees, it should move in the +x direction at full speed. Then should it be facing NE, or 45 degrees, it would move in the +x direction at half speed, and in the +y direction at half speed.

Step 8: Adding onEnterFrame Function

First we'll add the onEnterFrame function. Like I said above, this function will be called on every frame.

Step 9: Coding the Keys

Now we'll add functions which are called when a key is pressed.

Remember that when any key is pressed the keyPressed function is called. If it's one of the four keys the program is looking for, it will set that key's boolean to true and when that key is released the boolean will be set to false. Whenever a key is being held down, its boolean will be true.

Step 10: Rotating the Car

Step 11: Making the Car Wheels Turn

When the car turns we want it to look realistic, so we'll use the other images (carLeft and carRight) to make the wheels appear to be turning.

When the left key is pressed carLeft will appear, when the right key is pressed carRight will appear. When neither are being pressed carStraight will appear.

Step 12: Getting the Car's Rotation

I'll not go too deep into the explanation of the math, because it's either something you get or you don't. However, I'll try to explain it as best I can. Like I said, a lot of this was trial and error and working backwards, which I'll explain as I go along.

The way flash stores the rotation of an object is not from 0>360, it's from -180>180, where -180 = 180.

What this code does is takes the rotation of the car and gets the absolute value of it, so it will always be positive. Then it stores either 1 (if it was originally positive) or -1 (if it was originally negative) into the variable posNeg, which we will use later.

Step 13: Coding the Up Button

This is where all the majic happens.

In order to save room and make it easier to understand I won't paste the other code that was previously added before this step. All code in this step is added in between here:

Step 14: Moving the Car in the Y Direction

Instead of going through and explaining it, here is a table describing how the car should move in the y direction based on its rotation.

Degrees (°) Amount to move in Y
-180 -1
-135 -.5
-90 0
-45 .5
0 1
45 .5
90 0
135 -.5
180 -1

When the car is between -90 and 90 it is facing N to some degree and when it is between -180 and -90, or 90 and 180 it is facing S to some degree.

With some quick math I came up with this equation:

Step 15: Moving the Car in the X Direction

Determining how much the car should move in the x direction takes a bit more work.

Degrees (°) Amount to move in X
-180 0
-135 -.5
-90 1
-45 .5
0 0
45 .5
90 1
135 -.5
180 0

The first "if" deals with the car facing S and the second when it is facing N.

Step 16: Putting the Code Together

That is the basis of calculating the movement and this is what you should have so far in the onEnterFrame function:

Step 17: Adding Acceleration

If you were to run the program right now (which you probably can't since the code isn't complete) our car would not react to the up key being pressed. This is because increment=0. So we must add a line of code that increases this, but will stop increasing it once our car reaches top speed.

Step 18: Releasing the Gas

When you release the gas pedal on a car it begins to slowly decellerate due to many factors: Wind, drag, friction... so we must make the car slow down when the up arrow is not being pressed.

What the code does is if the Up key is not being pressed and increment is above 0, it starts to lower the increment. If the increment is not above 0 make it 0, or else the car will move backwards.

Notice that the code inside the "if" statement is the same code we added inside if (keyUpPressed) except that increment is now being lowered.

Step 20: Applying the Brake

Since the car cannot just rely on drag to stop it, we must also add a brake, which will be coded to the spacebar.

The code for this will have to be placed in multiple places.

This code states that if the spacebar is pressed while the up arrow key is pressed, decellerate, but at a slower pace. I then added code to an "if" statement we made earlier to make sure it was not executed if the spacebar was pressed.

We also need to add code when the up key is not being pressed and the spacebar is.

Step 21: Adding Speedometer Code

Last but not least we have to add the code which detects the speed and sends it to the speedometer.

Just after:


Step 22: Finalizing

That pretty much sums this tutorial up. What this program can do is pretty basic and I just wanted to outline the major parts in making a game like this. After grasping the concepts in this tutorial you can also code in the down key, make boundaries for the car, even make a racing game. I hope that you learned at least a little bit from this tutorial and thanks for reading it.

Final Code:

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.