- Home
- Tutorials
- Flash
- Intermediate
- Car Movement
Car Movement

Basic
onClipEvent (load) {
var speed:Number = new Number (0);
}
Now, that the speed variable is set, we can add script for increasing that variable. We don't want to raise the speed to one number (ex. 20), so we're going to make it increase slowly.
onClipEvent (enterFrame) {
if (Key.isDown (Key.UP)) {
speed += 1.5;
}
}
What this script does is increasing the speed for value of 1.5 every timeline frame if the UP arrow key is down. The if staitment checks to see if the condition in the brackets is true. For example: If the frame rate is set to 20 fps and the UP arrow key is down, then the speed will raise to value of 30 (20*1.5=30).
Now if you left the UP key, the car speed will stop increasing, but it won't decrease either. So you can edit the script to get:
onClipEvent (enterFrame) {
if (Key.isDown (Key.UP)) {
speed += 1.5;
}
speed = speed * 0.98;
}
This script is decreasing the speed by multiplying it with 0.98, that means the speed will get to 98% of the previous speed.
In order to move the car right and left we need to put _rotation scripts. And if we want to go backward, we also need a script for that. Put them all under the enterFrame event:
if (Key.isDown (Key.DOWN)) {
speed -= 0.8;
}
if (Key.isDown (Key.RIGHT)) {
_rotation += 8;
}
if (Key.isDown (Key.LEFT)) {
_rotation -= 8;
}
Now, to get the car move. Because the car can rotate, we need to know at what direction is turned. The easiest way to do that is by using the math sine and cosine, in Flash known as Math.sin & Math.cos. With those we can calculate the angle of the car position.
_x += Math.sin (_rotation * Math.PI / 180) * speed;
_y += Math.cos (_rotation * Math.PI / 180) * -speed;
You also need to put this under the enterFrame event. What Math.PI/180 does is it's convert the degrees (in this case _rotation) to radians (used for calculating sine and cosine. Then the sine and cosine are multiplied with the speed, so the car goes to the right direction.
We forgot something. The car has an unlimited speed. Not with this script:
if (Math.abs (speed) > 20) {
speed = 20;
}
if (speed < -10) {
speed = -10;
}
The first script limits the forward speed to a value of 20 and the second limits the backword to a value of 10.
And you can finally put a brake in the car, by simply adding the following script:
if (Key.isDown (Key.CONTROL)) {
speed -= speed / 10;
}
if (Key.isDown (Key.UP) & !Key.isDown (Key.CONTROL)) {
speed += 1.5;
}
What this script does is that it checks: is CTRL key NOT down. That's why the "!" is there. That means NOT.
So the basics are done. The car can accelerate, move right and left, go backward and even break! But what about little bugs, like rotating without even moving? And it wouldn't look nicer if it lefts wheel trail? See on the next page.
*All the previous scripts except the var speed:Number = new Number (0); script belongs to the onClipEvent (enterFrame) handler.

