development: resources
wrok / clients
flash games
flash projects
web sites
client list
 
Development (R&D)
resources
current development
 
about artifact interactive
contact

TUTORIAL: Building games in Flash 5
Part 1: Player movement and fire.

Author: David Doull
Date: 23/02/01
Download source files: tut1.zip


Step 3: Keyboard movement

Next we are going to add the code for detecting the keyboard. We will let the user control the spaceship using the arrow keys. Up arrow for up, left arrow for left etc.
Under the onClipEvent(load) code type the following.

onClipEvent (enterFrame) {

if (Key.isDown(Key.RIGHT)) { this._x+=moveSpeed; } else if (Key.isDown(Key.LEFT)) { this._x-=moveSpeed; }
if (Key.isDown(Key.DOWN)) { this._y+=moveSpeed; } else if (Key.isDown(Key.UP)) { this._y-=moveSpeed; } }

Now you should be able to use the arrow keys to move your spaceship smoothly around the screen. But what did those lines of code do?

The code is within an enterFrame clip event, which means that every time the movie clip enters a new frame the code is run. Effectively the code is run over and over again in a loop unless we remove or stop the movie clip.

But what key was pressed?

The first if statement checks if the key pressed is the right arrow (referenced as Key.RIGHT). If the right arrow was pressed then the code this._x+=moveSpeed; is run, otherwise it checks if the left arrow was pressed and if it was pressed the code this._x-=moveSpeed; is run.

The result of this code is to set a new x-position for the spaceship. If the right arrow is being pressed then this new x-position will be greater than the previous position, if the left arrow is being pressed then the new x-position will be less. How does it work?

this._x is a reference to the x-position of the associated movie clip.

In flash 4 you would have used a set Property command to set the x-position of a movie clip. In flash 5 you can do it by simply using _x. The word 'this' refers to the movie clip containing the script. So a line like this._x=10; would set the x-position of the associated movie clip to 10.

The += bit means 'add to the current value'. For example: this._x+=10; is exactly the same as this._x=this._x+10;

Simlialry the -= bit means 'subtract from the current value'. For example: this._x-=10; is exactly the same as this._x=this._x-10;

So why use += and -=? Because its less typing and its a popular shorthand that programmers use - hence its worth learning it so you can understand when other programmers use it.

 

Next >>